本文中為大家介紹使用java8 Stream API逐行讀取文件,以及根據某些條件過濾文件內容
1. 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();//只是測試用例,生產環境下不要這樣做異常處理
}
上面的程序輸出將在控制台中逐行打印文件的內容。
Never
store
password
except
in mind.
2.Java 8讀取文件–過濾行
在此示例中,我們將文件內容讀取為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();//只是測試用例,生產環境下不要這樣做異常處理
}
程序輸出。
password
我們將讀取給定文件的內容,並檢查是否有任何一行包含"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();
}
歡迎關注我的博客,里面有很多精品合集
- 本文轉載注明出處(必須帶連接,不能只轉文字):字母哥博客。
覺得對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創作動力! 。另外,筆者最近一段時間輸出了如下的精品內容,期待您的關注。