我有一個函數「a()」,它調用寫入stdout的另一個函數「b()」。我不能修改「B()」,但我希望能夠讀什麼「b」被寫和寫回標準輸出爲「B」的閱讀,意思是:Java - 讀取另一個線程正在寫入stdout/stderr - 如何?
public void a() {
// start a thread that listens to stdout.
// the thread should print a name to stdout after "b" print "Please enter your name"
b();
}
public void b() { // I cannot modify this function
System.out.println("Welcome! The time is " + System.currentTimeMillis());
System.out.println("Please enter your name");
String name = ...
// ... b reads here the name that the thread from function a() will write
// ...
System.out.println("This is the name that was entered: " + name);
}
我想過啓動「B 「在一個新的過程中,但我不知道如何在主函數中包裝」b「並使用命令行運行它 - 我很樂意提供建議。 如果它不是一個進程,我不知道如何實現將由「a()」激活的線程。
我試着使用:
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = stdin.readLine()) != null) {
...
}
但它沒有趕上什麼是 「b」 被寫入。
感謝您的幫助
你可以用'System.setIn'和'System.setOut'來完成它,但這是一個很糟糕的做法。參數化b的輸入和輸出流會好得多。 – trutheality
謝謝。我如何參數化b的輸入和輸出流? (我沒有訪問b的代碼)。 – Liz
@Liz如果你沒有訪問代碼,那麼你不能。你必須去user270349的解決方案。 – trutheality