Skip file creation in FileOutputStream when there is no data in Inputstream

This is a logging function that logs the flow of errors from an external program. Everything is working fine. But I do not want to generate a log file when there is no data in the error stream. A file of size zero is currently being created. 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.

+3
source share
2 answers

Just put the creation aside FileOutputStreamand PrintWriteruntil 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(); 
}

PrintWriter - , , . OutputStreamWriter, . , .

+3

, ,

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

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();
    }
}
+1

Source: https://habr.com/ru/post/1756559/


All Articles