反复将数据写入文件

问题描述

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

方法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();

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

解决方法

使用方法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
}