---
title: "文件 批量重命名"
author: "hecal"
date: "2011-12-19T20:59:33Z"
tags: []
categories: ["移动开发"]
slug: "untitled"
draft: false
lastmod: "2011-12-19T20:59:33Z"
id: 1317142
url: "https://hecal.iteye.com/blog/1317142"
---

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

 

 

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&lt; 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(".") &gt;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+"]");  
// }  
}  
}  
}  
}  
}