“你好,阿米戈!今天我們將探索一些超級有趣的東西:如何替換System.in 輸入流。”

System.in 是一個簡單的靜態InputStream變量,但您不能簡單地為其分配一個新值。但是您可以使用System.setIn() 方法。

首先,我們需要創建一個緩衝區,然後將一些值放入其中。然後我們將它包裝在一個知道如何使用 InputStream 協議從緩衝區中讀取數據的類中。

這是它的樣子:

代碼
public static void main(String[] args) throws IOException
{
 //Put data into a string
 StringBuilder sb = new StringBuilder();
 sb.append("Lena").append('\n');
 sb.append("Olya").append('\n');
 sb.append("Anya").append('\n');
 String data = sb.toString();

 //Wrap the string in a ByteArrayInputStream
 InputStream is = new ByteArrayInputStream(data.getBytes());

 //Replace in
 System.setIn(is);

 //Call an ordinary method that doesn't know about our changes
 readAndPrintLine();
}

public static void readAndPrintLine() throws IOException
{
 InputStreamReader isr = new InputStreamReader(System.in);
 BufferedReader reader = new BufferedReader(isr);

 while (true)
 {
  String line = reader.readLine();
  if (line == null) break;
  System.out.println(line);
 }
 reader.close();
 isr.close();
}

“Bilaabo!這是我見過的最有趣的例子。我不知道你能做到。謝謝。”

“不客氣,阿米戈。”