3

这是一个记录功能,它记录来自外部程序执行的错误流。一切正常。但是当错误流中没有数据时,我不想生成日志文件。目前它正在创建零大小的文件。请帮忙。

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

谢谢你。

4

2 回答 2

3

只需推迟创建FileOutputStreamandPrintWriter直到您需要它:

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,以便您可以显式指定编码。无论如何,这与这里的真正问题无关。

于 2010-07-26T12:49:28.690 回答
1

显而易见的事情就是改变

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();
    }
}
于 2010-07-26T12:49:36.867 回答