在Java中,可以使用不同的方法逐行读取文本文件。以下是一些逐行读取文件的方法,包括使用Streams或FileReader,并学习如何迭代行并根据某些条件筛选文件内容。

1.使用Files.lines() – 在Java 8中通过文件的行创建Stream

Files.lines()是Java 8的新功能。它将文件的所有行作为一个Stream进行读取。返回的Stream包含对打开文件的引用。通过关闭流来关闭文件。

重要的是要注意,文件内容不应在终端流操作执行期间被修改,否则终端流操作的结果是未定义的。

作为一种推荐的做法,应该在try-with-resources语句或类似的控制结构中使用Files.lines(),以确保在流操作完成后及时关闭流中的打开文件。

Path filePath = Paths.get("c:/temp", "data.txt"); try (Stream<String> lines = Files.lines( filePath )) { lines.forEach(System.out::println); } catch (IOException e) { //... } 

2.读取并筛选行

在此示例中,我们将文件内容作为行的流进行读取。然后,我们将筛选包含单词“password”的所有行。

为了进行筛选,我们传递一个Lambda表达式,这是一个Predicate的实例,给filter()方法。

Path filePath = Paths.get("c:/temp", "data.txt"); try (Stream<String> lines = Files.lines(filePath)) { List<String> filteredLines = lines .filter(s -> s.contains("password")) .collect(Collectors.toList()); filteredLines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } 

3.从小文件中读取所有行

如果文件大小较小,可以使用Files.readAllLines()方法将所有行从文件中读取到一个List中。默认情况下,文件中的字节会使用UTF-8字符集解码为字符。

注意,使用Files.readAllLines后,不需要显式关闭资源。

Path filePath = Paths.get("c:/temp", "data.txt"); List<String> lines = Files.readAllLines(filePath); for (String line : lines) { System.out.println(line); } 

4.使用FileReader逐行读取文件[已过时]

在Java 7之前,我们可以使用FileReader以各种方式读取文件。这只能作为参考,不应在Java 8或更高版本中使用,因为它对此用例没有额外的好处。

File file = new File("c:/temp/data.txt"); try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr);) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } 

5.Guava的Files.readLines()

最简单的解决方案之一是使用Google Guava的Files类和其readLines()方法。

try { List<String> lines = com.google.common.io.Files.readLines(file, Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } 

如果我们想在读取时处理这些行,可以使用LineProcessor。例如,在下面的代码中,我们将读取的行转换为大写。

// With LineProcessor LineProcessor<List<String>> lineProcessor = new LineProcessor<>() { final List<String> result = new ArrayList<>(); @Override public boolean processLine(final String line) throws IOException { result.add(StringUtils.capitalize(line)); return true; // keep reading } @Override public List<String> getResult() { return result; } }; try { List<String> lines = com.google.common.io.Files .asCharSource(file, Charset.defaultCharset()) .readLines(lineProcessor); } catch (IOException e) { e.printStackTrace(); } 

6.Apache Commons IO的FileUtils.readLines()

类似于Guava,Apache Commons IO库中的FileUtils类提供了一种单语句解决方案,用于逐行读取文件内容。操作结束时,文件始终会被关闭。

try { List<String> lines = FileUtils.readLines(file, Charset.defaultCharset()); } catch (IOException e) { e.printStackTrace(); } 

这些是逐行读取文件的Java示例。如果有问题,请在评论部分提出。