how to use java program to...rename all files in a directory according to a certain pattern,
for example,
1.txt
2.txt
3.txt
4.txt
.
.
.
Use the following code, all *.txt will be changed
to *.new (tested in UNIX)
import java.io.*;
public class temp{
public static void main(String[] args){
File f = new File(".");
File[] children = f.listFiles();
for (int i=0;i<children.length;i++){
String name = children[i].getName();
if (children[i].getName().endsWith(".txt")){
name = name.replaceAll(".txt",".new");
File f1 = new File(name);
children[i].renameTo(f1);
}
}
}
}
Things to note:
1. Directory is reprensented by class File. I used current directory (.), you can supply absolute path of the directory where you want to rename files.
2. Use listFiles to get all files in that directory.
3. I used some string methods to manipulate the file name.
4. You need to create a new File object and pass it to the method renameTo to change the name.
Hope this can help ....
import java.io.*;
public class temp{
public static void main(String[] args){
File f = new File(".");
File[] children = f.listFiles();
for (int i=0;i<children.length;i++){
String name = children[i].getName();
if (children[i].getName().endsWith(".txt")){
name = name.replaceAll(".txt",".new");
File f1 = new File(name);
children[i].renameTo(f1);
}
}
}
}
Things to note:
1. Directory is reprensented by class File. I used current directory (.), you can supply absolute path of the directory where you want to rename files.
2. Use listFiles to get all files in that directory.
3. I used some string methods to manipulate the file name.
4. You need to create a new File object and pass it to the method renameTo to change the name.
Hope this can help ....