本文中為大家介紹使用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();
}
歡迎關注我的博客,里面有很多精品合集
- 本文轉載注明出處(必須帶連接,不能只轉文字):字母哥博客,
覺得對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創作動力! ,另外,筆者最近一段時間輸出了如下的精品內容,期待您的關注,
- 《手摸手教你學Spring Boot2.0》
- 《Spring Security-JWT-OAuth2一本通》
- 《實戰前后端分離RBAC權限管理系統》
- 《實戰SpringCloud微服務從青銅到王者》
- 《VUE深入淺出系列》
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/139923.html
標籤:Java
上一篇:多執行緒并發詳解
