替换文件中包含的文件名,并使用java以新名称重命名文件

时间:2013-07-27 20:09:26

标签: java replace rename

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

例如:

  

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

1 个答案:

答案 0 :(得分: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();
    }