Java Example - File Renaming
The following example demonstrates the use of the File class'soldName.renameTo(newName)method to rename a file.
Before running the following program, you need to create a test file in the current directory.example-test.txt。
Main.java file
import java.io.File;
import java.io.IOException;
public class ExampleTest {
public static void main(String[] args) throws IOException {
//Old file or directory
File oldName = new File("./example-test.txt");
//New file or directory
File newName = new File("./example-test-2.txt");
if (newName.exists()) { //Make sure the new file name does not exist
throw new java.io.IOException("file exists");
}
if(oldName.renameTo(newName)) {
System.out.println("Renamed");
} else {
System.out.println("Error");
}
}
}
The output of running the above code is:
RenamedOther Extensions