0

我一直在尝试通过查找和替换名称中的子字符串来重命名给定文件夹中的文件和文件夹。此外,文件的名称也包含在它们的内容中。我需要将其替换为新名称。

例如:

在所有文件和文件夹名称以及文件内容中将“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();
        }       
    }
}
4

1 回答 1

1

看起来您并没有in在阅读后关闭输入 ( ) 文件,这将使该文件保持打开状态 - 在 *nix 下,重命名仍然可以工作,但在 Windows 下会失败:

  • 使用finally块来确保资源已关闭..但只有在您确定它已打开之后。

在此期间,请允许我建议对代码进行另一项更改:

  • 将“声明”移动到代码中可以进行的绝对最后一点。避免提前声明。在这种情况下,两者inout都不必要地提前声明。还有其他的;我会把它留给你解决。

因此,对于输入文件:

    // Read the file contents
    try {
        BufferedReader in = new BufferedReader(new FileReader(file));
        // If you got this far, the file is open...
        // use try/finally to ensure closure.
        try {
            while((line = in.readLine()) != null) {
                fullText+=line+"\n";
            }
        }
        finally {
          in.close();
        }
    }
    catch(FileNotFoundException e) {
        e.printStackTrace();
    }
    catch(IOException e) {
        e.printStackTrace();
    }

对于输出文件:

    // Write the replaced text to file
    try {
        BufferedWriter out = new BufferedWriter(new FileWriter(file));
        try {
            out.write(fullText);
        }
        finally {
            out.close();
        }
    }
    catch(FileNotFoundException e) {
        e.printStackTrace();
    }
    catch(IOException e) {
        e.printStackTrace();
    }
于 2013-07-28T03:57:53.943 回答