Java Rename File | Directory with example code

Renaming a file is required mostly application. Like you renaming a file name in windows, mac or Linux OS. This all are programs, same as you build applications. This tutorial will learn and do coding for How to java rename file and directory. Here we are considered Directory as a folder which contains files.

Java Rename File, directory with Example code

To Java rename file you need just use renameTo method. This is inbuild method in java which return a boolean value. True for success and false for failed to rename the file. Changing the name of the file in java programming is comes under the Java file handling (like create, delete, Move file etc).

Java Rename File

Let’s see the how to use File.renameTo method rename file in java example. Here in this example file “newFile.txt” name changing to “cook.txt“.

Output: GIF file to of output and code structure

Java Rename File Example

How to Java rename files in directory?

As you see the upper example was changing the file name only. What if the file is inside any directory (folder)? How you will change the name?

It’s a simple as above example you just need to pass complete file path with name in the place of the file name. See the below code for it.


Question: How to Java rename directory?

Answer: It’s a very simple as same as example of file renaming. You just need to pass the folder/rename name. Same as below code. “dest” is directory name for change to “new” as name.

Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JRE: 11.0.1
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.14.1
Java version 11
All Java renamee File are in Java 11, so it may change on different from Java 9 or 10 or upgraded versions.|

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.