Skip to content

Java Rename File | Directory with example code

  • by

Renaming a file is required mostly application. Like you renaming a file name in windows, mac, or Linux OS. These all are programs, the 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 that contains files.

Java Rename File, directory with Example code

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

Java Rename File

Let’s see 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

Java Rename File Example

How to Java rename files in a 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 very simple as the same example of file renaming. You just need to pass the folder/rename name. Same as below code. “dest” is the directory name for change to “new” as a 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)
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

Your email address will not be published. Required fields are marked *