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 8 逐行读取文件
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(); }
之路 on it Road.com
Java 8 读取文件找出特定的行
将文件内容作为行流读取。
然后过滤出所有包含“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(); }
日期:2020-09-17 00:10:18 来源:oir作者:oir