Tutorial :Skip creating file in FileOutputStream when there is no data in Inputstream



Question:

This is a logging function which logs error stream from the execution of an external program. Everything works fine. But I do not want to generate the log file when there is no data in error stream. Currently it is creating zero 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.


Solution:1

Simply defer the creating of the FileOutputStream and PrintWriter until you 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 a big fan of PrintWriter - the fact that it just swallows all exceptions concerns me. I'd also use OutputStreamWriter so that you can explicitly specify the encoding. Anyway, that's aside from the real question here.


Solution:2

The obvious thing to do is to change

FileOutputStream fos = new FileOutputStream(logFile);  PrintWriter pw = new PrintWriter(fos);  ....     if (pw != null){     ...     }  

to

FileOutputStream rawLog = null;  try {      PrintWriter Log = null;      ....         if (log == null) {             rawLog = new FileOutputStream(logFile);             log = new PrintWriter(log, "UTF-8");         }         ...  } finally {      // Thou shalt close thy resources.      // Icky null check - might want to split this using the Execute Around idiom.      if (rawLog != null) {          rawLog.close();      }  }  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »