To rename a file, we can use File.renameTo()
function from java.io
package. However, renameTo()
function requires a new File
object with the new name that we want to name the source file, instead of just passing the new name to renameTo()
function.
So, to rename a file, we need to create two File
objects, one for the original name and another for the new name that we want.
File file = new File("D:\\alpha.txt");
file.renameTo(new File("D:\\beta.txt"));
If you want to verify the existence of the file before renaming it, you can use File.exists()
function. To check if it is a file or directory, you can include File.isFile()
function in the condition.
Full Example
package com.techstackjournal;
import java.io.File;
public class RenameFile {
public static void main(String[] args) {
File file = new File("D:\\alpha.txt");
if (file.isFile()) {
file.renameTo(new File("D:\\beta.txt"));
System.out.println("File has been renamed");
} else {
System.out.println("File doesn't exists");
}
}
}