2017-11-20 8 views
0

나는 해결책을 찾기 위해 여러 개의 SFO Links e.g.을 조사했습니다. 내가 가지고있는 코드는 내 동료가 작성한 약 30 개의 메소드가 있고 중첩 루프가 포함 된 코드입니다. 이 문제는 Eclipse에서 코드를 실행하려고 할 때 콘솔 출력에 긴 꼬리 문제가있는 것입니다.콘솔과 파일 모두 인쇄

내가보고있는 것은 모든 메소드 내에서 모든 sysout 명령을 변경하지 않고 콘솔뿐만 아니라 파일에 결과 (중간 결과)를 인쇄하는 것이 었습니다. 내가 지금 무슨 짓을

는 디스플레이에이

PrintStream out = new PrintStream(new FileOutputStream("output.txt")); 
System.setOut(out); 

같은 그러나 파일이 쓰기 전용 및 없습니다.

+0

출력을 복제하는 기본 'OutputStream'이 있는지 (체크하지 않았 음) 확인해야합니다. 여러개의'OutputSteam' (상속받은 하나,'Collection'의 나머지 부분)에 쓰고, 그 인스턴스를'System.out'에 설정하는 자신의 클래스 – AxelH

+2

특별히 Eclipse에 관한 것입니까? Eclipse에는 모든 출력을 콘솔뿐만 아니라 파일에도 기록하는 설정이 있습니다. 실행중인 구성에 대한 구성 실행> 공통> 출력 파일 확인 및 위치 선택. –

답변

1

당신은 콘솔과 텍스트 파일 PrintStream 비교적 쉽게 확장

1

모두 인쇄 TeeOutputStream를 사용하여 출력 스트림을 분기 할 수있다.

class ForkOut extends PrintStream { 
    // The other stream to write to. 
    final PrintStream[] others; 

    public ForkOut(PrintStream o1, PrintStream... others) { 
     super(o1); 
     this.others = others; 
    } 

    @Override 
    public void write(int b) { 
     super.write(b); 
     // Echo every write to the other streams. 
     for (PrintStream o : others) { 
      o.write(b); 
     } 
    } 

    @Override 
    public void write(byte[] buf, int off, int len) { 
     super.write(buf, off, len); 
     // Echo every write to the other streams. 
     for (PrintStream o : others) { 
      o.write(buf, off, len); 
     } 
    } 
} 

public void test(String[] args) throws FileNotFoundException { 
    System.out.println("Hello"); 
    System.setOut(new ForkOut(System.out, new PrintStream(new FileOutputStream("output.txt")))); 
    System.out.println("Hello again!"); 
} 
0

System.setOut() 방법 (귀하의 경우 인의 PrintStream out) 원하는 스트림에 System.out 스트림에 모든 출력을 리디렉션 같은 것을보십시오. 결과를 out.print(String) 메소드와 콘솔에 System.out.print(String) 메소드로 작성하는 것을 고려해 볼 수 있습니다.