編寫java工具類,支持根據編號批量修改指定目錄下文件及文件夾名稱。例如:編號爲10001、30541……根據編碼與姓名匹配表批量修改文件名爲張三、李四……。減少手工操作繁瑣操作。
demo下載地址
package com.zp.myjavademo.filecollection;
import com.alibaba.fastjson.JSON;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
/**
* author : zp
* e-mail : zhangping1
* time : 2019-08-29 13:17
* desc :遍歷文件目錄,根據原文件名的客戶號匹配json中客戶姓名進行重命名
* version: 1.0
*/
public class FileUtils {
private static String jsonStr;
private static FileNameBean bean = new FileNameBean();
private static String jsonPathDir = "/Users/theappleofna/workspace/android_demo/MyTestCollection/MyJavaDemo/src/main/java/com/zp/myjavademo/filecollection/filename.json";
private static String filePathDir = "/Users/theappleofna/workspace/test/files/";
public static void main(String[] args) throws IOException {
// 從目錄讀取json文件
jsonStr = readJsonData(jsonPathDir);
// System.out.println("得到當前路徑json===" + jsonStr);
// 解析。將匹配關係解析道json實體類
bean = JSON.parseObject(jsonStr, FileNameBean.class);
// 遍歷得到所有文件數組
File file = new File(filePathDir);
String[] fileNameList = file.list();
System.out.println("讀取文件列表---" + Arrays.toString(fileNameList));
// 進性重命名
renameFile(fileNameList);
}
/**
* 遍歷文件目錄,根據原文件名的客戶號匹配json中客戶姓名進性重命名
*
* @param fileName
* @author zhangping
*/
private static void renameFile(String[] fileName) {
for (int i = 0; i < fileName.length; i++) {
System.out.println("源文件名==" + fileName[i]);
for (int n = 0; n < bean.getData().size(); n++) {
if (bean.getData().get(n).getUSERSEQ().equals(fileName[i])) {
System.out.println("該客戶索引==" + n);
File oldFileName = new File(filePathDir + fileName[i]);
File newFileName = new File(filePathDir + bean.getData().get(n).getCIFNAME() + "影像資料");
System.out.println("oldName===" + oldFileName + "\n newFileName==" + newFileName);
if (oldFileName.renameTo(newFileName)) {
System.out.println("重命名成功~~");
} else {
System.out.println("重命名失敗!!!");
}
}
}
}
}
public static String readJsonData(String pactFile) throws IOException {
StringBuffer strbuffer = new StringBuffer();
File myFile = new File(pactFile);// "D:"+File.separatorChar+"DStores.json"
if (!myFile.exists()) {
System.err.println("Can't Find " + pactFile);
}
try {
FileInputStream fis = new FileInputStream(pactFile);
InputStreamReader inputStreamReader = new InputStreamReader(fis, "UTF-8");
BufferedReader in = new BufferedReader(inputStreamReader);
String str;
while ((str = in.readLine()) != null) {
strbuffer.append(str); // new String(str,"UTF-8")
}
in.close();
} catch (IOException e) {
e.getStackTrace();
}
// System.out.println("讀取文件結束util");
return strbuffer.toString();
}
}