In this Java 8 tutorial, learn to read a file line by line using stream api. Also learn to iterate through lines and filter the file content based on some conditions.
1. Java 8 read file – line by line
In this example, I will read the file content in lines as stream
and fetch each line one at a time and check it for word "password"
.
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(); }
The above program output will print the content of the file in the console line by line.
Never store password except in mind.
2. Java 8 read file – filtering stream of lines
In this example, we will read the file content as stream of lines as. Then we will filter all lines which have the word "password"
in it.
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(); }
Program output.
password
We will read the content of the given file and check if any line contains word "password"
then print it.
3. Java 7 – Read file using FileReader
Till java 7, we could read a file using FileReader
in various ways.
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(); }
That’s all for Java example to read a file line by line. Please put your questions on comments section.
Happy Learning !!
Raj
Hi ,
I want read certain word like ” Result ” . I need to print all line after result line.
please share me code.
Thanks in advance
Saravana
Hi,
Have assigned with a task to create a Data Collector using NIO and TFTP.
From the Network Elements i have to get large files using TFTP and Java NIO.
Could you please help me to do this.
Lokesh Gupta
You must try yourself first, if struck anywhere then let me know.
Muzzammil Ayyubi
Awesome Lokesh…really nice article.
Neha Kanojia
Hi,
I am student of MTech.I have to do thesis work,where I have to read text and find the maximum probability of a particular Indian languages with Java.Suggest me how would I do that….
prathap
hi i’m a vivid follower of