java - Skip creating file in FileOutputStream when there is no data in Inputstream -


this logging function logs error stream execution of external program. works fine. not want generate log file when there no data in error stream. creating 0 size file. please help.

fileoutputstream fos = new fileoutputstream(logfile); printwriter pw = new printwriter(fos);  process proc = runtime.getruntime().exec(externalprogram);  inputstreamreader isr = new inputstreamreader(proc.geterrorstream()); bufferedreader br = new bufferedreader(isr); string line=null; while ( (line = br.readline()) != null) {    if (pw != null){       pw.println(line);       pw.flush();     } } 

thank you.

simply defer creating of fileoutputstream , printwriter until need it:

printwriter pw = null;  process proc = runtime.getruntime().exec(externalprogram);  inputstreamreader isr = new inputstreamreader(proc.geterrorstream()); bufferedreader br = new bufferedreader(isr); string line; while ( (line = br.readline()) != null) {    if (pw == null)    {       pw = new printwriter(new fileoutputstream(logfile));    }    pw.println(line);    pw.flush();  } 

personally i'm not big fan of printwriter - fact swallows exceptions concerns me. i'd use outputstreamwriter can explicitly specify encoding. anyway, that's aside real question here.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -