2011-02-05 55 views
1

控制檯文本有沒有辦法從控制檯輸出已由輸出:獲取Java中

System.out.print("blabla"); 

+3

你想去哪裏找回呢?你想在你打印的程序中檢索它嗎?或者你想在另一個程序中閱讀它? – yankee 2011-02-05 10:13:19

+0

我希望通過該計劃的另一部分進行檢索,使某種通用的測試儀。通過查看答案,我發現這個問題的更好的解決方案通過使環境測試儀 – SirLenz0rlot 2011-02-07 13:30:44

回答

5

如果你希望能夠看到你已經寫到控制檯,你需要編寫自己的PrintStream實現,只是封裝現有PrintStream,不管它是應該寫,然後商店代表(種所有的方法)來包裹(原件)PrintStream做實際工作。你如何存儲消息完全取決於你的需要(只存儲最後寫入字符串,存儲地圖時間戳 - >字符串或其他)。一旦你有了這個,你可以用你自己的實現(通過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

如果我理解你,你可以從Java啓動過程和讀是這樣的輸出:

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

如果您需要任何處理更復雜的控制(通過PID訪問,名稱等),這是真正好的庫: Java Service Wrapper