CodeGym /课程 /Java 核心 /编写你自己的流:System.in 的包装类

编写你自己的流:System.in 的包装类

Java 核心
第 8 级 , 课程 7
可用

“你好,阿米戈!今天,我们将探索一些超级有趣的东西:如何替换 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();
}

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

“不客气,阿米戈。”

评论 (2)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Ocean 级别 22,China,Hong Kong
19 九月 2022
System.setIn() : 对标准输入流的重新分配
momoshenchi 级别 22,Wenzhou,China
31 八月 2020
终于看懂了 System.setIn() 是文中重点 可以把System.in 实例换为其他实例,文中替换为new ByteArrayInputStream(data.getBytes()). ByteArrayInputStream作用是从byte[]数组读取字节