`
hecal
  • 浏览: 74718 次
社区版块
存档分类
最新评论

文件 批量重命名

阅读更多

前几天要处理一些图片资料,从看到有人提供了一个批处理的方法,但是只能处理单个目录下的文件命名,我给改动了一下变成可以递归处理很多层目录了,算是半个原创,跟大家分享一下~~

 

 

import java.io.File;
/**
* 文件 批量重命名
* @author
*
*/
public class BatchRenameFile {
//输出日志
public static volatile boolean isDebug = false;
private static int j=0;
public static void main(String[] args) {
// String root = "C:/Users/hello/Documents/android/方案/upload/hd_imgfile_rename";//文件夹目录
String root = "C:/Users/hello/Documents/android/方案/upload/test";//文件夹目录
File [] fs = new File(root).listFiles();

String newName = "a";
System.out.println();
BatchRenameFile.isDebug = true;
try {
rename(fs,newName);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 批量 重命名 文件名
* @param files 文件列表(文件夹或文件)
* @param newName 新文件名
* @throws Exception 可能的异常
*/
public static void rename(File [] files ,String newName) throws Exception {
if(files == null || newName == null || newName.trim().length()==0){
return;
}
for(int i=0 ; i< files.length ; i++){
if(files[i] != null && files[i].exists()){
File f = files[i];

int lastIndex = f.getAbsolutePath().lastIndexOf(File.separator);
//父目录
String path = f.getAbsolutePath().substring(0 , lastIndex+1);
if(f.isFile()){
//文件,保持后缀名
String extensions = f.getName().lastIndexOf(".") >0 ?
( f.getName().substring(f.getName().lastIndexOf(".")) ) : "";
f.renameTo(new File(path + newName +j+ extensions));
j++;
if(isDebug){
System.out.println("文件["+f.getName()+"],重命名为["+ path + newName+j+extensions+"]");
}
}else{

//改动处
File [] fs = new File(f.getAbsolutePath()).listFiles();
rename(fs, newName);
//文件夹
// f.renameTo(new File(path + newName));
// if(isDebug){
// System.out.println("文件夹["+f.getName()+"],重命名为["+ path + newName+"]");
// }
}
}
}
}
}

0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics