Java –如何将文件读入列表?

谁践踏了优雅 2023-02-15 05:18 79阅读 0赞

在Java中,几乎没有办法将文件逐行读取到List

  1. Java 8流

    List result;

    1. try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
    2. result = lines.collect(Collectors.toList());
    3. }
  2. Java 7

    Files.readAllLines(new File(fileName).toPath(), Charset.defaultCharset());

3.经典的BufferedReader示例。

  1. List<String> result = new ArrayList<>();
  2. BufferedReader br = null;
  3. try {
  4. br = new BufferedReader(new FileReader(fileName));
  5. String line;
  6. while ((line = br.readLine()) != null) {
  7. result.add(line);
  8. }
  9. } catch (IOException e) {
  10. e.printStackTrace();
  11. } finally {
  12. if (br != null) {
  13. br.close();
  14. }
  15. }

1.文件->列表

1.1虚拟文件

d:\\server.log

  1. a
  2. b
  3. c
  4. d
  5. 1
  6. 2
  7. 3

1.2将文件读入List

JavaExample.java

  1. package com.mkyong.example;
  2. import java.io.BufferedReader;
  3. import java.io.File;
  4. import java.io.FileReader;
  5. import java.io.IOException;
  6. import java.nio.charset.Charset;
  7. import java.nio.file.Files;
  8. import java.nio.file.Paths;
  9. import java.util.ArrayList;
  10. import java.util.List;
  11. import java.util.stream.Collectors;
  12. import java.util.stream.Stream;
  13. public class JavaExample {
  14. public static void main(String[] args) {
  15. String filename = "d:\\server.log";
  16. try {
  17. List list = readByJavaClassic(filename);
  18. list.forEach(System.out::println);
  19. } catch (IOException e) {
  20. e.printStackTrace();
  21. }
  22. }
  23. private static List readByJava8(String fileName) throws IOException {
  24. List<String> result;
  25. try (Stream<String> lines = Files.lines(Paths.get(fileName))) {
  26. result = lines.collect(Collectors.toList());
  27. }
  28. return result;
  29. }
  30. private static List readByJava7(String fileName) throws IOException {
  31. return Files.readAllLines(new File(fileName).toPath(), Charset.defaultCharset());
  32. }
  33. private static List readByJavaClassic(String fileName) throws IOException {
  34. List<String> result = new ArrayList<>();
  35. BufferedReader br = null;
  36. try {
  37. br = new BufferedReader(new FileReader(fileName));
  38. String line;
  39. while ((line = br.readLine()) != null) {
  40. result.add(line);
  41. }
  42. } catch (IOException e) {
  43. e.printStackTrace();
  44. } finally {
  45. if (br != null) {
  46. br.close();
  47. }
  48. }
  49. return result;
  50. }
  51. }

输出量

  1. a
  2. b
  3. c
  4. d
  5. 1
  6. 2
  7. 3

参考文献

  1. Java 8 Stream –逐行读取文件

标签: java 读取文件 流

翻译自: https://mkyong.com/java/java-how-to-read-a-file-into-a-list/

发表评论

表情:
评论列表 (有 0 条评论,79人围观)

还没有评论,来说两句吧...

相关阅读

    相关 文件读入

    文件的读入还有另一种方法,就是用EOF函数判断是否读入到文件的末尾,然后控制一直的输入,用while一直循环下去 include <fstream> inc