登录 | 首页 -> 华新鲜事 -> 社会百科 | 切换到:传统版 / sForum | 树形列表
how to use java program to...
<<始页  [1]  末页>> 

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
.
.
.
[hidden (1-21 10:10, Long long ago)] [ 传统版 | sForum ][登录后回复]1楼

check FileSystemView class[逃课专家 (1-21 11:44, Long long ago)] [ 传统版 | sForum ][登录后回复]2楼

Use the following code, all *.txt will be changedto *.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 ....
[天下 (1-21 12:02, Long long ago)] [ 传统版 | sForum ][登录后回复]3楼

(引用 天下:Use the following code, all *.txt will be changedto *.new (tested in UNIX) import java.io.*; public class temp{ public stat...)thanks[hidden (1-21 13:37, Long long ago)] [ 传统版 | sForum ][登录后回复]4楼

(引用 逃课专家:check FileSystemView class)ok, thanks[hidden (1-21 13:37, Long long ago)] [ 传统版 | sForum ][登录后回复]5楼


<<始页  [1]  末页>> 
登录 | 首页 -> 华新鲜事 -> 社会百科 | [刷新本页] | 切换到:传统版 / sForum