2010-07-26 5 views
3

외부 프로그램의 실행에서 오류 스트림을 기록하는 로깅 기능입니다. 모든 것이 잘 작동합니다. 그러나 오류 스트림에 데이터가없는 경우 로그 파일을 생성하고 싶지 않습니다. 현재 크기가 0 인 파일을 만들고 있습니다. 도와주세요.Inputstream에 데이터가 없을 때 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

감사합니다 @ 존 소총을 변경하는 것입니다. 나는 내 실수를 발견했다. FileWriter는 실제로 함수의 매개 변수이기 때문에 PrintWriter 만 지연 시키려고했습니다. 내 매개 변수 형식을 File로 변경 한 다음 루프 내에서 FileOutputStream을 만들어야하는 것 같습니다. – Sujee

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