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.
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!
Please disable your ad blocker and refresh the window to use this website.