「こんにちは、アミーゴ! 今日は非常に興味深いことをいくつか探っていきます。 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();
}

「ビラーボ! これは私が見た中で最も興味深い例です。あなたがそんなことができるとは知りませんでした。ありがとう。」

「どういたしまして、アミーゴ」