Main Tutorials

Java 8 Stream – Read a file line by line

In Java 8, you can use Files.lines to read file as Stream.

c://lines.txt – A simple text file for testing

line1
line2
line3
line4
line5

1. Java 8 Read File + Stream

TestReadFile.java

package com.mkyong.java8;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class TestReadFile {

	public static void main(String args[]) {

		String fileName = "c://lines.txt";

		//read file into stream, try-with-resources
		try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

			stream.forEach(System.out::println);

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

Output


line1
line2
line3
line4
line5

2. Java 8 Read File + Stream + Extra

This example shows you how to use Stream to filter content, convert the entire content to upper case and return it as a List.

TestReadFile2.java

package com.mkyong.java8;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class TestReadFile2 {

	public static void main(String args[]) {

		String fileName = "c://lines.txt";
		List<String> list = new ArrayList<>();

		try (Stream<String> stream = Files.lines(Paths.get(fileName))) {

			//1. filter line 3
			//2. convert all content to upper case
			//3. convert it into a List
			list = stream
					.filter(line -> !line.startsWith("line3"))
					.map(String::toUpperCase)
					.collect(Collectors.toList());

		} catch (IOException e) {
			e.printStackTrace();
		}

		list.forEach(System.out::println);

	}

}

Output


LINE1
LINE2
LINE4
LINE5

3. BufferedReader + Stream

A new method lines() has been added since 1.8, it lets BufferedReader returns content as Stream.

TestReadFile3.java

package com.mkyong.java8;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class TestReadFile3{

	public static void main(String args[]) {

		String fileName = "c://lines.txt";
		List<String> list = new ArrayList<>();

		try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {

			//br returns as stream and convert it into a List
			list = br.lines().collect(Collectors.toList());

		} catch (IOException e) {
			e.printStackTrace();
		}
	
		list.forEach(System.out::println);

	}

}

Output


line1
line2
line3
line4
line5

4. Classic BufferedReader And Scanner

Enough of Java 8 and Stream, let revisit the classic BufferedReader (JDK1.1) and Scanner (JDK1.5) examples to read a file line by line, it is working still, just developers are moving toward Stream.

4.1 BufferedReader + try-with-resources example.

TestReadFile4.java

package com.mkyong.core;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class TestReadFile4{

	public static void main(String args[]) {

		String fileName = "c://lines.txt";

		try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

			String line;
			while ((line = br.readLine()) != null) {
				System.out.println(line);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

4.2 Scanner + try-with-resources example.

TestReadFile5.java

package com.mkyong.core;

import java.io.File;
import java.io.IOException;
import java.util.Scanner;

public class TestReadFile5 {

	public static void main(String args[]) {

		String fileName = "c://lines.txt";

		try (Scanner scanner = new Scanner(new File(fileName))) {

			while (scanner.hasNext()){
				System.out.println(scanner.nextLine());
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

References

  1. Java 8 File.lines()
  2. Java 8 Stream
  3. Java BufferedReader

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
15 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Priyanka Wagh
4 years ago

Which one is the fastest way to read and print file among these all ways?

muddassir
3 years ago
Reply to  Priyanka Wagh

I had the same query

Marcelo
6 years ago

Hi Mk, what would you recommend to process a large file, let say 50 gb, to for example, delete duplicate lines?

Ana
6 years ago

You have used Files.lines. Shouldn’t the stream be closed after Files.lines?

Nawel
5 years ago

Hello @mykong,

Thank you for your examples. I would like to parse a YAML file to object without using jakson or known librairies. Only Java8.

Could you help?
Thank you.
Nawel

maskier
6 years ago

Hi MK,
¿how can we read a txt file in a deployed webapp? ¿Do we have to create a folder in the src>resources>static folder ?
Thanks

Dmitry
6 years ago

Thanks!

mohit
6 years ago

Hi MK,

Is there any way through which we can read row record on the basis of value. For example my csv file is :-

ProductID,ProductName,price,availability,type
12345,Anaox,300,yes,medicine
23456,Chekmeter,400,yes,testing

i want to get the row whose ProductID is ‘23456’. i was checking the new CsvReader(“D:\roche-poc.csv”).getRawRecord() method. but it doesn’t have any method parameters.

Thanks

Subbaiah
4 years ago
Reply to  mohit

Supplier<Stream> supl = () -> {
try {
return Files.lines(Paths.get(“Products.csv”));
} catch (IOException e) {
e.printStackTrace();
}
return Stream.empty();
};

List header = Arrays.asList(supl.get().findFirst().get().split(“,”));
String r = supl.get().filter(l -> l.split(“,”)[header.indexOf(“ProductID”)].equals(“12345”)).findAny().orElse(“”);
System.out.println(r);

stelios
7 years ago

Are streams faster than scanner, at this issue? I ve benchmarked a simple text file to time scanner vs lines.collect and the scanner is always faster by far

cal
7 years ago

hi MK,

i have a file with data in dual lines

eg:
line1:hello, how are
you, ?
line2: hi, how are you?

how do i read line1, as one line, rather than 2 lines?

much appreciate your response for this

-Cal

stelios
7 years ago
Reply to  cal

string tokenizer may do the trick for ya

cybertraque
8 years ago

hi MK , you have a spike with lambda ?
thx

mkyong
8 years ago
Reply to  cybertraque

??? Sorry, don’t get you.

Ankita gondalia
6 years ago
Reply to  mkyong

he might be saying Do lambda expressions have Spikes on their heasd or not 😀