Opening and closing the same file several times against opening the file for a long time

I write File whenever there is a change in the content in the JTextArea field. Each time, I decided to open and close the contents of the file in accordance with the change event.

Sort of,

 public void addToLogFile(String changeContent) { try { PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(currentLogFile,true))); pw.print(changeContent); pw.close(); } catch (FileNotFoundException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } 

Instead of opening and closing the file each time, I thought that we can open it at the initial stage and dump it when necessary. Finally close it in the final phase.

In the initial phase of the program:

 PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(currentLogFile,true))); 

Then somewhere in the code where necessary,

 pw.print(changeContent); // Most frequent usage 

In the final phase of the program:

 pw.close(); 

Which one will be more effective? Under what condition should I choose?

+6
source share
2 answers

More effective, of course, would be opening the file once. Opening a file every time is quite expensive.

In one case, this can be useful when new writes to a file occur once for a long time, so the OS does not need to store an open file handler.

Another case when I will consider opening and closing it each time is when the records do not happen so often, and you want other processes to write to the file. Or, maybe, when you want each record to be visible right after it is written, but then you better just drop the buffer.

+4
source

Do not keep the file open is an option if you have many such text fields where each of them is associated with a different file. Then, if the number of text fields approaches the limit of an open file, most likely your program will not be able to open any other files, sockets, or anything else when each of the fields will occupy one file descriptor.

But, of course, this is a purely theoretical consideration. The limitation of open files is usually around 2000, and I can hardly imagine an application with 2000 text input fields.

At the same time, earlier versions of the unix search utility took care of closing and then reopening the moved directories to avoid problems with the disappearance of file decriptors. But that was in the early days when the limit was 20 or so.

+3
source

Source: https://habr.com/ru/post/987261/


All Articles