Java最佳和最快的方式来编辑文本文件

问题描述


我需要快速有效地编辑大量文本文件!我能做的最好的事情是什么? 我已经想出了这个功能:
private boolean edit(File source)
{
    if (!source.getAbsolutePath().endsWith(".java")) //Java text files only
        return false;

    String l,str = "",orig = ""; 
    try
    {
        BufferedReader r = new BufferedReader(new FileReader(source));
        while ((l = r.readLine()) != null)
        {
            orig = str += l+"\n";
        }
        r.close();

        for (Entry<String,String> e : mappings.entrySet()) //Replacing string by HashMap mappings!
            str = fastReplace(str,e.getKey(),e.getValue()); //Faster alterntive to String#replaceAll
        
        if (!str.equals(orig))
        {   
            BufferedWriter bf = new BufferedWriter(new FileWriter(source));
            bf.write(str);  
            
            bf.close();
            return true;
        }
    }
    catch (Exception e) 
    {
        doLog(e.toString()); //Logging exception but unimportant for us...
    }
    return false;
}

我发现我的函数有点笨拙,因为它首先需要将文本文件读取为字符串,然后对其进行编辑并写回。问题是。有没有更好,更快的方法来编辑文本文件?我的意思是例如不必将其转换为字符串然后再写回。例如,是否有一种方法可以直接将文件编辑为文本文件或将其写入,而不会覆盖文件中相同的未更改部分,或者有一种更快的读取和写入文件的方法?还是我的功能实际上已经最快了?
如果有人想知道我的“ fastReplace”功能做什么,然后检查此Faster alternatives to replace method in a Java String?,但我认为这并不重要。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)