views:

43

answers:

2

Hi Guys,

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.

+3  A: 

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.

Jon Skeet
Thanks @Jon Skeet. I found my mistake. I tried to defer only the PrintWriter, because FileOutputStream is actually is a parameter of the function. Looks like I need to change my parameter type to File then create FileOutputStream inside the loop.
Sujee
+1  A: 

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();
    }
}
Tom Hawtin - tackline