Java File I/O – How to rename a file (change file name)
This code example shows how to change the name of a file.
import java.io.File;
/**
*
* @author www.javabout.com
*/
public class Main {
public void renameFile(String file, String toFile) {
File toBeRenamed = new File(file);
if (!toBeRenamed.exists() || toBeRenamed.isDirectory()) {
System.out.println(“File does not exist: “ + file);
return;
}
File newFile = new File(toFile);
//Rename
if (toBeRenamed.renameTo(newFile)) {
System.out.println(“File has been renamed.”);
} else {
System.out.println(“Error renmaing file”);
}
}
public static void main(String[] args) {
new Main().renameFile(“C:\\temp\\file1.txt”, “C:\\temp\\file2.txt”);
}
}









Leave your response!