2011-02-05 2 views
1

에서 콘솔 텍스트를 가져 오기? 이은 (이름 등을 pid로 액세스) 당신이 어떤 프로세스의보다 정교한 제어가 필요한 경우에 의해 출력 된 콘솔에서 출력을 검색하는 방법이 있나요 자바

ProcessBuilder builder = new ProcessBuilder("/bin/bash"); 
builder.redirectErrorStream(true); 
Process process = builder.start(); 

OutputStream stdin = process.getOutputStream(); 
InputStream stderr = process.getErrorStream(); 
InputStream stdout = process.getInputStream(); 

BufferedReader reader = new BufferedReader (new InputStreamReader(stdout)); 
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin)); 

String input = scan.nextLine(); 
... 

: 나는 당신을 이해하면

+3

은 어디를 검색 할 수 있습니까? 인쇄 한 프로그램에서 불러 오시겠습니까? 아니면 다른 프로그램에서 읽고 싶습니까? – yankee

+0

나는 일종의 일반 테스터를 만들기 위해 프로그램의 다른 부분에서 그것을 검색하고 싶었다. 이 답을 살펴 봄으로써, 테스터에게 환경을 보여줌으로써이 문제에 대한 더 나은 해결책을 찾았습니다. – SirLenz0rlot

답변

5

대표단 (모두 방법)을 실제 작업을 수행하는 포장 된 (원래) PrintStream에 붙여 넣습니다. 메시지를 완전히 저장하는 방법은 필요에 따라 다릅니다 (마지막으로 작성된 String 만 저장하고 타임 스탬프의 맵을 저장하는 등). 당신이이 있으면, 당신은 (System.setOut()를 통해) 자신의 구현 System.out을 대체 할 수

public class RememberAllWrittenTextPrintStream extends PrintStream { 

    private static final String newLine = System.getProperty("line.separator"); 

    private final StringBuffer sb = new StringBuffer(); 
    private final PrintStream original; 

    public RememberAllWrittenTextPrintStream(PrintStream original) { 
     this.original = original; 
    } 

    public void print(double d) { 
     sb.append(d); 
     original.print(d); 
    } 

    public void print(String s) { 
     sb.append(s); 
     original.print(s); 
    } 

    public void println(String s) { 
     sb.append(s).append(newLine); 
     original.println(s); 
    } 

    public void println() { 
     sb.append(newLine); 
     original.println(); 
    } 

    public void printf(String s, Object... args) { 
     sb.append(String.format(s, args)); 
     original.printf(s, args); 
    } 


    // ..... 
    // the same for ALL the public methods in PrintStream.... 
    // (your IDE should help you easily create delegates for the `original` methods.) 

    public String getAllWrittenText() { 
     return sb.toString(); 
    } 

} 
또한 스레드 안전을 돌볼 필요가 있습니다

(StringBuffer를이 스레드 안전하지만이보다 더 필요할 수 있습니다).

위가 있으면

수행 할 수 있습니다

RememberAllWrittenTextPrintStream ps 
     = new RememberAllWrittenTextPrintStream(System.out); 
System.setOut(ps); 
System.out.print("bla"); 
System.out.print("bla"); 
ps.getAllWrittenText(); // should now return "blabla" 

편집 : 사용 println() 구현을 추가 플랫폼에 독립적 newLine.

+0

데코레이터 패턴, nice (+1) –

+0

이미 몇 가지 기본 기능이 아닌 것 같았습니다. 내 문제에 대한 더 깨끗한 해결책. 감사 – SirLenz0rlot

0

, 당신은 자바에서 프로세스를 시작하고이 같은 출력의 읽을 수 있습니다 정말 좋은 라이브러리 : 당신은 이미 콘솔에 쓴 것을 볼 수 있도록하려면, 당신은 단순히 기존 PrintStream 래핑 자신의 PrintStream 구현이 다음 작성하도록되어 어떤 상점을 작성해야 Java Service Wrapper

관련 문제