Java 8 – Read file line by line

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 !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

6 thoughts on “Java 8 – Read file line by line”

  1. Hi ,

    I want read certain word like ” Result ” . I need to print all line after result line.

    please share me code.

    Thanks in advance

    Reply
  2. 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.

    Reply
  3. 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….

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.