3 Examples to read a text file line by line using java


In order to read a text file line by line using Java code you can make use of multiple options, let us see 3 examples,

Sample text file sample.txt
Line 1
Line 2
Line 3
Line 4
Line 5



Example 1: Using BufferedReader and FileReader from java.io package,
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class JavaReadTextFile {

    public static void main(String[] args) throws IOException {

        String fileName = "/Users/proj/src/main/sample.txt";
        FileReader file = new FileReader(fileName);
        BufferedReader bufferedReader = new BufferedReader(file);

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



Example 2: Using Java 7 Files from java.nio package,
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class JavaReadTextFile {

    public static void main(String[] args) throws IOException {
        String fileName = "/Users/proj/src/main/sample.txt";
        Path path = Paths.get(fileName);
        Files.lines(path).forEach(System.out::println);
    }
}



Example 3: Using Java 8 Streams and Files
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class JavaReadTextFile {

    public static void main(String[] args) throws IOException {
        String fileName = "/Users/proj/src/main/sample.txt";
        Stream<String> linesStream = Files.lines(Paths.get(fileName));
        linesStream.forEach(System.out::println);
    }
}
Java Read Text file line by line example


Have Questions? Post them here!
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.