【问题标题】:Writing data to file repeatedly重复写入数据到文件
【发布时间】:2020-11-10 05:44:37
【问题描述】:

我必须反复读取文件和写入数据。我想到了两种方法:-

方法#1

while(readLine ...) {
    // open the file to write 
    br.write("something);    //write to file
    br.close();
    // close the file
}

方法#2

// open the file to write
while(readLine...)
    br.write("something");
}
br.close();

我应该每次打开和关闭文件还是在程序开始时打开一次并在应用所有业务逻辑后关闭文件。哪个是更好的方法?有人有缺点吗?

【问题讨论】:

  • 一般情况下,如果您从一个文件中读取以重复写入另一个文件,您会希望保留您要打开的文件以进行写入,直到写入完成。如果您要进行多次写入,我还建议您使用 BufferedWriter / BufferedOutputStream

标签: java filereader read-write


【解决方案1】:

使用方法#2。

每次写入的打开和关闭都不必要地缓慢。此外,如果您不小心以追加模式打开文件,您最终会不断覆盖旧文件并以仅包含您编写的最后一行的输出文件结束。

所以,使用方法#2:打开文件(可能以附加模式,也可能不是,这取决于您的需要),写下您要写的所有内容,关闭文件,完成。

【讨论】:

    【解决方案2】:

    您应该打开文件的输入或输出流一次并完成所有业务逻辑,然后在最后关闭连接。 编写此类代码的更好方法是:

    try{
        // open the file stream
        // perform your logic
    }
    catch(IOException ex){
      // exception handling
    }
    finally{
       // close the stream here in finally block
    }
    

    您可以在不需要编写 finally 块的资源中使用 try。在 try 块中打开的流将自动关闭。

    try(BufferedReader br = new BuffredReader(...)/*add writer here as well*/){
        // perform your logic here
    }
    catch(IOException ex){
       // exception handling
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 2012-07-13
      • 2013-07-06
      • 2020-07-11
      相关资源
      最近更新 更多