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!

Top Hashtags:

Advertisements

Advertisements




Advertisements