从文件中逐行读取字符串

1. IO流读取

  • Inputstream字节流按字节读取
  • Reader字符流按字符读取
  • InputStreamReader将字节流包装为字符流
  • BufferedReaderInputStreamReader包装实现逐行读取
public static List<String> getListFromfile(String file) {
        List<String> wordList = new ArrayList<>();
        try (InputStream inputStream = PyProcessService.class.getResourceAsStream(file);
             BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
            String word;
            while ((word = reader.readLine()) != null) {
                wordList.add(word.trim());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wordList;
}

2. Files.lines方法

  • Path表示文件路径可以不用考虑不同平台路径分割符的差异
  • Files.lines方法获得文件每行字符串构成的流,方便快捷
public static void main(String[] args) {
        try (Stream<String> lines = Files.lines(Paths.get("./src/main/resources/suggest_words.csv"))) {
            lines.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容