4 回答

TA貢獻1829條經驗 獲得超7個贊
InputStream您可以使用負責處理的自定義實現通過另一個線程發送輸入。我下面的版本也允許用戶輸入。
請注意,此解決方案并不完美,但應該讓您對如何操作有一個粗略的印象。
public static void main(final String[] args) {
System.out.println("What now?");
DoubleSourceInputStream inputStream = new DoubleSourceInputStream();
final Scanner scanner = new Scanner(inputStream);
new Thread() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
inputStream.addBytes(("do task " + i + "\r\n").getBytes());
}
// to signal we are done, otherwise the queue would be polled forever
inputStream.addBytes(new byte[] { -1 });
}
}.start();
final String response = scanner.nextLine();
scanner.close();
System.out.println("Finished: " + response);
}
static class DoubleSourceInputStream extends InputStream {
BlockingQueue<Byte> buffer = new LinkedBlockingQueue<>();
@Override
public int read() throws IOException {
if (System.in.available() > 0)
return System.in.read();
try {
return buffer.take().intValue();
}
catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public void addBytes(byte[] bytes) {
for (byte b : bytes) {
buffer.offer(Byte.valueOf(b));
}
}
}

TA貢獻1875條經驗 獲得超3個贊
與其重新發明輪子,不如使用終端的功能來完成。
您通常使用 運行程序的圖像java -jar program.jar
,您現在需要將其運行為java -jar program.jar <input.txt
,其中input.txt
包含您在交互運行時通常從鍵盤傳遞的所有數據。
這僅在您的程序是可預測的情況下才有效,但不可預測程序的計時結果通常是無用的,除非運行數千次。

TA貢獻1821條經驗 獲得超6個贊
使用 Main 類作為引導程序方法,并在對InputStream(輸入)和PrintStream(輸出)進行操作的單獨類中實現被測試的代碼。
import java.util.Scanner;
public class Main {
public static void main(final String[] args) {
MyCode code = new MyCode(System.in, System.out);
code.run();
}
}
現在您不再局限于System.in為. 從測試引導代碼時,只需將 System.in 和 out 替換為測試代碼寫入和讀取的純流。System.outMyCode
添加回答
舉報