JAVA8系列教程-读取文件
温馨提示:
本文最后更新于 2020年04月21日,已超过 2,014 天没有更新。若文章内的图片失效(无法正常加载),请留言反馈或直接联系我。
在此Java 8教程中,学习使用stream api逐行读取文件。另外,还要学习遍历行并根据某些条件过滤文件内容。
1. Java 8读取文件–逐行
在此示例中,我将按行读取文件内容,stream并一次获取每一行并检查是否有word "password"。
Path filePath = Paths.get("c:/temp", "data.txt");
//try-with-resources
try (Stream<String> lines = Files.lines( filePath ))
{
lines.forEach(System.out::println);
}
catch (IOException e)
{
e.printStackTrace();
}
上面的程序输出将在控制台中逐行打印文件的内容。
Never store password except in mind.
2. Java 8读取文件–过滤行流
在此示例中,我们将文件内容读取为行流as。然后,我们将过滤其中包含单词的所有行"password"。
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();
}
程序输出。
password
我们将读取给定文件的内容,并检查是否有任何一行包含word,"password"然后打印出来。
3. Java 7 –使用FileReader读取文件
到Java 7为止,我们可以通过FileReader多种方式使用读取文件。
private static void readLinesUsingFileReader() throws IOException
{
File file = new File("c:/temp/data.txt");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine()) != null)
{
if(line.contains("password")){
System.out.println(line);
}
}
br.close();
fr.close();
}
这就是Java示例逐行读取文件的全部内容。请在评论部分提出您的问题。
正文到此结束
- 本文标签: 其他
- 本文链接: https://www.v8en.com/article/250
- 版权声明: 本文由SIMON原创发布,转载请遵循《署名-非商业性使用-相同方式共享 4.0 国际 (CC BY-NC-SA 4.0)》许可协议授权