本文中为你们介绍使用java8 Stream API逐行读取文件,以及根据某些条件过滤文件内容vue
在此示例中,我将按行读取文件内容并在控制台打印输出。java
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();//只是测试用例,生产环境下不要这样作异常处理 }
上面的程序输出将在控制台中逐行打印文件的内容。spring
Never store password except in mind.
在此示例中,咱们将文件内容读取为Stream。而后,咱们将过滤其中包含单词"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();//只是测试用例,生产环境下不要这样作异常处理 }
程序输出。springboot
password
咱们将读取给定文件的内容,并检查是否有任何一行包含"password"而后将其打印出来。前后端分离
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(); }
以为对您有帮助的话,帮我点赞、分享!您的支持是我不竭的创做动力! 。另外,笔者最近一段时间输出了以下的精品内容,期待您的关注。测试