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.
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“.
public class RenameFileExample
public static void main(String args)
File oldFile =new File("newFile.txt");
File newFile =new File("cook.txt");
System.out.println("Rename renamed successfully");
System.out.println("File Renaming failed");
Output: GIF file to of output and code structure
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.
File oldFile =new File("dest/newFile.txt");
File newFile =new File("dest/cook.txt");
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.
File oldFile =new File("dest");
File newFile =new File("new");
Note: This example (Project) is developed in IntelliJ IDEA 2018.2.6 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Java version 11
All Java renamee File
arein Java 11, so it may change on different from Java 9 or 10 or upgraded versions.|