To rename a file in Java, you can use the File class and its renameTo() method.
Here's an example:
import java.io.File;
public class RenameFileExample {
public static void main(String[] args) {
File oldFile = new File("oldfile.txt");
File newFile = new File("newfile.txt");
boolean result = oldFile.renameTo(newFile);
if (result) {
System.out.println("File renamed successfully.");
} else {
System.out.println("File rename failed.");
}
}
}
In this example, we create two File objects - one for the old file name ("oldfile.txt") and one for the new file name ("newfile.txt"). We then call the renameTo() method on the old file object, passing in the new file object as an argument. This method returns a boolean value indicating whether the file was successfully renamed or not. We then print a message to the console indicating whether the rename operation was successful or not.
Note that the renameTo() method can also be used to move a file to a different directory by specifying a new path in the File object for the new file name.