Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open and Close of same File multiple times vs Opening File for long time

I am writing to a File whenever any change of content in JTextArea field.I have decided to open and close the file content each time as per the change event.

Something like ,

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 may be we could open it at initial phase and dump content whenever required. Finally close it at the end phase.

At Initial Phase of program:

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

Then somewhere in code, wherever needed,

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

At Final Phase of program:

pw.close();

Which one will be more efficient ? Under what condition, Do I have to choose one ?

like image 422
Dinesh Avatar asked May 15 '15 09:05

Dinesh


1 Answers

More effective would definitely be opening the file once. Opening the file everytime is quite costly.

One case it may be useful is when new entries to the file happen once in a long while, so the OS doesn't need to hold open file handler.

Another case in which I would consider opening and closing it each time is when writes happen not so often and you want to let other processes write to the file. Or maybe when you want to ensure each entry is visible just after writing it, but then you should rather simply flush the buffer.

like image 121
ki92 Avatar answered Nov 14 '22 22:11

ki92