简体   繁体   中英

Writing data to file repeatedly

I have to read file and write data repeatedly. I thought of two methods:-

Method #1

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

Method #2

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

Should I open and close the file everytime or open it open once in the beginning of program and close the file in the end after applying all the business logic. Which one is the better approach? Does anyone have some disadvantage?

Use Method #2.

Opening and closing for every write is needlessly slow. Also, if you're not careful to open the file in append mode , you end up constantly overwriting the old file and finish with an output file containing only the last line you wrote.

So, Use Method #2 : open the file (possibly in append mode, possibly not, depending on your needs), write everything you're going to write, close the file, DONE.

You should open the input or output stream to the file once and complete all the business logic and then at the end close the connections. The better approach to write such a code would be:

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

You can use try with resources where you don't need to write finally block. Streams opened in try block would be closed automatically.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM