java8 Stream流逐行處理文本文件
本文中為大家介紹使用java8 Stream API逐行讀取文件,以及根據(jù)某些條件過濾文件內(nèi)容
1. Java 8逐行讀取文件
在此示例中,我將按行讀取文件內(nèi)容并在控制臺打印輸出。
Path filePath = Paths.get('c:/temp', 'data.txt'); //try-with-resources語法,不用手動(dòng)的編碼關(guān)閉流try (Stream<String> lines = Files.lines( filePath )) { lines.forEach(System.out::println);} catch (IOException e) { e.printStackTrace();//只是測試用例,生產(chǎn)環(huán)境下不要這樣做異常處理}
上面的程序輸出將在控制臺中逐行打印文件的內(nèi)容。
Neverstorepasswordexceptin mind.
2.Java 8讀取文件?過濾行
在此示例中,我們將文件內(nèi)容讀取為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();//只是測試用例,生產(chǎn)環(huán)境下不要這樣做異常處理}
程序輸出。
password
我們將讀取給定文件的內(nèi)容,并檢查是否有任何一行包含'password'然后將其打印出來。
3.Java 7 ?使用FileReader讀取文件
Java 7之前的版本,我們可以使用FileReader方式進(jìn)行逐行讀取文件。
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流逐行處理文本文件的詳細(xì)內(nèi)容,更多關(guān)于java8 Stream流處理文件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
