2013-04-05 2 views
0

내 콘솔의 출력을 텍스트 파일로 보여주고 싶습니다.콘솔에서 java에서 텍스트 파일로 출력하기

public static void main(String [ ] args){ 
    DataFilter df = new DataFilter(); 
    df.displayCategorizedList(); 
    PrintStream out; 
    try { 
     out = new PrintStream(new FileOutputStream("C:\\test1.txt", true)); 
     System.setOut(out); 
    } catch (FileNotFoundException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 

} 

화면에 내 결과가 올바르게 표시되지만 텍스트 파일이 표시되지 않습니까? 테스트 파일은 genereted이지만 비어 있습니다 ??

+0

'df.displayCategorizedList();'는 stdout으로 출력합니까? 그럼 당신은 아마도'System.setOut()'뒤에 그것을 이동해야합니다 –

+0

나는 자바에서 새로운 오전 좀 더 힌트를 주시기 바랍니다 –

+0

이 주제는 꽤 철저하게 다루고있는 것 같습니다 [http : // stackoverflow. com/questions/1994255/console-output-to-a-txt-file을 작성하는 방법). –

답변

5

시스템 출력 스트림을 파일로 설정 한 후에는 "console"로 인쇄해야합니다.

또한 finally 블록을 사용하여 항상 스트림을 닫으십시오. 그렇지 않으면 데이터가 파일로 플러시되지 않을 수 있습니다.

+0

o/p 스트림을 파일로 설정 한 다음 c 폴더에 저장합니다. –

0

나는 다음과 같은 방법 제안 :

public static void main(String [ ] args){ 
    DataFilter df = new DataFilter(); 
    try (PrintStream out = new PrintStream(new FileOutputStream("d:\\file.txt", true))) { 
      System.setOut(out); 
      df.displayCategorizedList(); 
    } catch (FileNotFoundException e) { 
     System.err.println(String.format("An error %s occurred!", e.getMessage())); 
    } 
} 

이 사용을 JDK 7 시도 -과 - 자원 기능 - 당신이 그 (FileNotFoundException이 같은) 예외를 다루는 것을 의미하며 또한 finally 블록 대신 리소스를 닫습니다.

JDK 7을 사용할 수없는 경우 다른 응답에서 제안 된 방법 중 하나를 사용하십시오.

관련 문제