java - Open and Close of same File multiple times vs Opening File for long time -
i writing file
whenever change of content in jtextarea
field.i have decided open , close file content each time per change event.
something ,
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 , closing file each time, thought may open @ initial phase , dump content whenever required. close @ 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); // frequent usage
at final phase of program:
pw.close();
which 1 more efficient ? under condition, have choose 1 ?
more effective opening file once. opening file everytime quite costly.
one case may useful when new entries file happen once in long while, os doesn't need hold open file handler.
another case in consider opening , closing each time when writes happen not , want let other processes write file. or maybe when want ensure each entry visible after writing it, should rather flush buffer.
Comments
Post a Comment