需求:如标题所示
public class FileTest {
public static void main(String[] args) throws IOException {
File file = new File("D:"+File.separator+"test");
long start = System.currentTimeMillis();
renameDir(file);
long end = System.currentTimeMillis();
System.out.println("本次操作花费时间:" + (end - start));
}
private static void renameDir(File file) {
if(file.isDirectory()){
File results[] = file.listFiles();
if(results != null){
for (int i = 0; i < results.length; i++) {
renameDir(results[i]);
}
}
}else {
if(file.isFile()){
String fileName = null;
if(file.getName().contains(".")){
fileName = file.getName().substring(0, file.getName().lastIndexOf(".")) + "1.txt";
}else {
fileName = file.getName() + ".txt";
}
File newFile = new File(file.getParentFile(),fileName);
file.renameTo(newFile);
}
}
}
}

这段代码实现了一个功能,遍历指定目录下的所有文件,如果文件是文本文件,则在其原始名称基础上添加 '1' 或 '.txt' 后缀进行重命名。整个操作的时间消耗也在代码中进行了打印。
1255

被折叠的 条评论
为什么被折叠?



