我一直在尝试通过查找和替换名称中的子字符串来重命名给定文件夹中的文件和文件夹。此外,文件的名称也包含在它们的内容中。我需要将其替换为新名称。
例如:
在所有文件和文件夹名称以及文件内容中将“XXX”更改为“KKK”:
原始文件名:0001_XXX_YYY_ZZZ.txt
新文件名:0001_KKK_YYY_ZZZ.txt
以下是我正在使用的代码。
当我在不调用函数 replaceText() 的情况下运行以下代码时,它会重命名文件和文件夹。但是,当我尝试更改文件的文本然后重命名文件和文件夹时;文件内容已更改,但文件和文件夹的重命名均失败。
请帮忙。
public class FindReplaceAnywhere {
public static void main(String[] args) {
String find = "XXX";
String replace = "KKK";
String baseLoc = "D:\\0001_XXX_YYY_ZZZ";
FindReplaceAnywhere obj = new FindReplaceAnywhere();
File baseLocObj = new File(baseLoc);
LinkedList<File> baseFolderList = new LinkedList<File>();
// Add base folder object to list
baseFolderList.add(baseLocObj);
// Get list of files in the folder
for(File file: baseLocObj.listFiles()) {
baseFolderList.add(file);
}
// Rename the files, folders & contents of files
obj.rename(baseFolderList, find, replace);
}
public void rename(LinkedList<File> fileList, String find, String replace) {
String tempStr = null;
int beginIndex = 0;
int endIndex = 0;
File tempFile;
System.out.println(">>> Batch Rename Process Begins >>>\n");
for(File aFile:fileList) {
// If Object is File, change the text also
if(aFile.isFile()) {
replaceText(aFile,find,replace);
}
}
for(File aFile: fileList) {
System.out.println("Processing>>>");
System.out.println(aFile.getPath());
if(aFile.getName().contains(find)) {
// Get the name of File object
beginIndex = aFile.getPath().length() - aFile.getName().length();
endIndex = aFile.getPath().length();
tempStr = aFile.getPath().substring(beginIndex, endIndex);
tempStr = tempStr.replace(find, replace);
}
else {
System.out.println("Error: Pattern not found\n");
continue;
}
tempFile = new File(aFile.getParentFile(),tempStr);
boolean success = aFile.renameTo(tempFile);
if(success) {
System.out.println("File Renamed To: "+tempFile.getName());
}
else {
System.out.println("Error: Rename Failed\nPossible Cause: File is open in another application");
}
System.out.println("");
}
}
/**
* Replace the text of file if it contains filename
*/
public void replaceText(File file, String find, String replace) {
String fullText = "";
String line = "";
String fileName = "";
String replaceName = "";
BufferedReader in;
BufferedWriter out;
// Read the file contents
try {
in = new BufferedReader(new FileReader(file));
while((line = in.readLine()) != null) {
fullText+=line+"\n";
}
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
// Replace the text of file
fileName = file.getName().substring(0, file.getName().indexOf("."));
replaceName = fileName.replace(find, replace);
fullText = fullText.replace(fileName, replaceName);
// Write the replaced text to file
try {
out = new BufferedWriter(new FileWriter(file));
out.write(fullText);
out.close();
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
}