How to build a Java 8 stream from System.in / System.console()?

前端 未结 3 2036
眼角桃花
眼角桃花 2021-01-01 15:09

Given a file, we can transform it into a stream of strings using, e.g.,

Stream lines = Files.lines(Paths.get(\"input.txt\"))

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-01 15:34

    Usually the standard input is read line by line, so what you can do is store all the read line into a collection, and then create a Stream that operates on it.

    For example:

    List allReadLines = new ArrayList();
    
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    String s;
    while ((s = in.readLine()) != null && s.length() != 0) {
        allReadLines.add(s);
    }
    
    Stream stream = allReadLines.stream();
    

提交回复
热议问题