“你好,阿米戈!今天,我们将探索一些超级有趣的东西:如何替换 System.in 输入流。”
System.in 是一个简单的 static 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();
}
“比拉博!这是我所见过的最有趣的示例。我不知道你能做这个。谢谢。”
“不客气,阿米戈。”
GO TO FULL VERSION