“你好,阿米戈!今天,我们将探索一些超级有趣的东西:如何替换 System.in 输入流。”

System.in 是一个简单的 static InputStream 变量,但不能直接为其赋予新值。不过,你可以使用 System.setIn() 方法。

首先,我们需要创建一个缓冲区,并将一些值放入其中。然后,将该缓冲区包装在一个类中,该类知道如何使用 InputStream 协议从缓冲区读取数据。

看起来如下所示:

代码
public static void main(String[] args) throws IOException
{
 //将数据放入字符串
 StringBuilder sb = new StringBuilder();
 sb.append("莉娜").append('\n');
 sb.append("奥丽雅").append('\n');
 sb.append("安雅").append('\n');
 String data = sb.toString();

 //将字符串包装在 ByteArrayInputStream 中
 InputStream is = new ByteArrayInputStream(data.getBytes());

 //替换位置
 System.setIn(is);

 //调用一个不知道我们更改的普通方法
 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();
}

“比拉博!这是我所见过的最有趣的示例。我不知道你能做这个。谢谢。”

“不客气,阿米戈。”