2010-07-26 60 views
3

這是一個日誌記錄功能,它記錄執行外部程序時的錯誤流。一切正常。但是我不想在錯誤流中沒有數據時生成日誌文件。目前它正在創建零大小的文件。請幫忙。當輸入流中沒有數據時,跳過在FileOutputStream中創建文件

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

謝謝。

回答

3

簡單地推遲FileOutputStreamPrintWriter的創建,直到你需要它:我

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,以便您可以明確指定編碼。無論如何,這不是真正的問題。

+0

感謝@喬恩飛碟雙向。我發現我的錯誤。我試圖推遲只有PrintWriter,因爲FileOutputStream實際上是該函數的一個參數。看起來我需要將我的參數類型更改爲File,然後在循環內部創建FileOutputStream。 – Sujee 2010-07-26 12:57:30

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(); 
    } 
} 
相關問題