1. 程式人生 > 程式設計 >java8 Stream流逐行處理文字檔案

java8 Stream流逐行處理文字檔案

本文中為大家介紹使用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();
}

以上就是java8 Stream流逐行處理文字檔案的詳細內容,更多關於java8 Stream流處理檔案的資料請關注我們其它相關文章!