Java – Rename File

To rename file in Java, you can use File.renameTo() function. renameTo() function is called on the original file. And file with new name is passed as argument to the renameTo().

In this tutorial, we will learn how to rename a file in Java.

Following is the sequence of steps one has to follow to rename a file in Java using File.rename().

  1. Prepare the File object for the file you would like to rename.
  2. Prepare a File object with the new file name
  3. Call renameTo() on the original file (from step 1) with file object(from step 2) passed as argument.

Rename File using File.renameTo()

In this example, we rename a file from data.txt to newdata.txt.

If the renaming operation is successful, renameTo() returns true. Else the function returns false.

RenameFile.java

import java.io.File;

/**
 * Java Example Program to Rename File
 */

public class RenameFile {

	public static void main(String[] args) {
		File originalFile = new File("files/data.txt");
		File newFile = new File("files/newdata.txt");
		
		//rename file
		boolean isRenameDone = originalFile.renameTo(newFile);
		
		//print if the rename is successful
		System.out.println("Rename Done: "+isRenameDone);
	}
}

Output

Rename Done: true

renameTo() returned true, meaning the rename is successful.

ADVERTISEMENT

Negative Scenario – File to rename is not present

In this example, we are changing the name of a file that is not present.

RenameFile.java

import java.io.File;

/**
 * Java Example Program to Rename File
 */

public class RenameFile {

	public static void main(String[] args) {
		File originalFile = new File("files/data1.txt");
		File newFile = new File("files/newdata.txt");
		
		//rename file
		boolean isRenameDone = originalFile.renameTo(newFile);
		
		//print if the rename is successful
		System.out.println("Rename Done: "+isRenameDone);
	}
}

The file is not present, so the rename could not be successful. renameTo() function returns false.

Output

Rename Done: false

Negative Scenario – New file name already exists

In this Java program, we try to change the file name to a new name. But the catch is that there is already a file with the new name.

RenameFile.java

import java.io.File;

/**
 * Java Example Program to Rename File
 */

public class RenameFile {

	public static void main(String[] args) {
		File originalFile = new File("files/data1.txt");
		File newFile = new File("files/data.txt");
		
		//rename file
		boolean isRenameDone = originalFile.renameTo(newFile);
		
		//print if the rename is successful
		System.out.println("Rename Done: "+isRenameDone);
	}
}

Run the program, and you will get false returned by renameTo() function.

Output

Rename Done: false

Conclusion

In this Java Tutorial, we learned how to rename a File in Java and how to be sure if the rename operation is successful.