Rename files in Java
The renameTo() allows you to rename a file under any operating system such as Windows for example. It returns true if the file is successfully renamed. You should always check the returned value to be sure that the file has been renamed.package com.codeurjava.File;Execution:
import java.io.File;
public class RenameFileJava {
public static void main(String[] argv) {
Old File = new File("c:\\test\\ancienFichier.txt");
File nouveau = new File("c:\\test\\nouveauFichier.txt");
if(old.renameTo(new))
System.out.println("The file "+old+" has been renamed.");
else
System.out.println("Failed! The file "+old+" could not be renamed.");
}
}
The file c:\test\ancienFichier.txt has been successfully renamed.
Rename multiple Files with a certain extension
The following code renames a list of files that belong to a directory. In this example, c:\test\example is the directory, the files are renamed this way: f1.txt, f2.txt, etc. Only files with the txt extension are renamed.package com.codeurjava.File;Runtime:
import java.io.File;
import java.io.IOException;
public class RenameFilesJava {
public static void main(String[] argv) throws IOException {
File folder = new File("c:\\test");
File[] list = folder.listFiles();
for (int i = 0; i < liste.length; i++) {
if (list[i].isFile()) { // if it's a file
//fetch the current file
File f = new File("c:\\test\\"+list[i].getName());
String extension = "";
Old String = list[i].getName();
//verify that the extension is txt
int index = old.lastIndexOf('.');
if (index > 0) {
extension = old.substring(index+1);
}
if(extension.equals("txt")){
New string = "f"+i+".txt";
f.renameTo(new File("c:\\test\\"+new));
System.out.println(old+" renamed => "+new);
}
else{
System.out.println(ancient+" is not a txt file);
}
}
}
System.out.println("Operation complete!");
}
}
anc1.txt renamed => f0.txt
anc2.txt renamed => f1.txt
anc3.txt renamed => f2.txt
img_01.jpg is not a txt
table.sql is not a txt
Operation complete!
Resources:
https://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo(java.io.File)
https://stackoverflow.com/questions/1158777/rename-a-file-using-java