工作中遇到实体类的文件名需要批量修改如"test0x01","text0x02","text0x03","text0x04"......改为
"newFile0x01","newFile0x02","newFile0x03"......
重命名前
重命名后
代码:
package FileStream;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
public class reTest1 {
public static void main(String[] args) {
//要修改的包的路径
String path = "E:\\file\\src\\renameTest";
//要修改的新的文件名是什么
String newName="newFile";
//0代表从文件名头部开始
int start=0;
//8代表从上面的位置开始前8位
int end=4;
getRenameFiles(path,start,end,newName);
}
//修改类名的方法
private static void reJavaClassName(String filePath, String oldName, String newText) {
try {
// 读取文本文件的内容
Path path = Paths.get(filePath);
StringBuilder contentBuilder = new StringBuilder();
try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(path.toFile()), StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
contentBuilder.append(line).append(System.lineSeparator());
}
}
String contentNew = contentBuilder.toString();
System.out.println(contentNew);
// 替换内容
String modifiedContent = contentNew.replace(oldName, newText);
// 将修改后的内容写回文本文件
Files.write(path, modifiedContent.getBytes(), StandardOpenOption.WRITE);
System.out.println("文本文件内容已成功修改!");
} catch (IOException e) {
System.out.println("修改文本文件内容时出现错误:" + e.getMessage());
}
}
private static void getRenameFiles(String path,int start,int end,String newName) {
File file = new File(path);
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
System.out.println("目录:" + files[i].getPath());
getRenameFiles(files[i].getPath(),start,end,newName);
} else {
reJavaClassName(files[i].getPath(), files[i].getName().replace(".java",""), files[i].getName().replace(".java","").replace(files[i].getName().substring(start,end),newName));
reName(files[i].getPath(), files[i].getPath().replace(files[i].getName().substring(start,end), newName));
}
}
} else {
System.out.println("文件:" + file.getPath());
}
}
// 修改文件名
public static boolean reName(String absolutePathName, String newAbsoluteName) {
File file = new File(absolutePathName);
if (file == null)
return false;
if (!file.exists()) {
System.out.println("文件 " + absolutePathName + " 不存在");
return false;
} else {
file.renameTo(new File(newAbsoluteName));
return true;
}
}
}