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

后端 未结 2 820
忘了有多久
忘了有多久 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<String> doc =
          new BufferedReader(new InputStreamReader(resource,
              StandardCharsets.UTF_8)).lines().collect(Collectors.toList());
    }
    
    0 讨论(0)
  • 2021-02-02 06:38

    You can use Apache Commons IOUtils#readLines:

    List<String> doc = IOUtils.readLines(inputStream, StandardCharsets.UTF_8);

    0 讨论(0)
提交回复
热议问题