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);
In the final phase of the program:
pw.close();
Which one will be more effective? Under what condition should I choose?
source share