equivalent to Files.readAllLines() for InputStream or Reader?

后端 未结 2 816
忘了有多久
忘了有多久 2021-02-02 05:48

I have a file that I\'ve been reading into a List via the following method:

List doc = java.nio.file.Files.readAllLines(new File(\"/path/to/src/res         


        
2条回答
  •  不思量自难忘°
    2021-02-02 06:33

    An InputStream represents a stream of bytes. Those bytes don't necessarily form (text) content that can be read line by line.

    If you know that the InputStream can be interpreted as text, you can wrap it in a InputStreamReader and use BufferedReader#lines() to consume it line by line.

    try (InputStream resource = Example.class.getResourceAsStream("resource")) {
      List doc =
          new BufferedReader(new InputStreamReader(resource,
              StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
    }
    

提交回复
热议问题