How to read a plain text file in Java
This tutorial shows several ways for reading plain text files in Java.
The techniques we use here are totally JDK built-in and don’t depend on external libraries.
1- BufferedReader
The most common way for reading plain text files in Java is through using a FileReader wrapped by a BufferedReader. This technique is very efficient for reading large text files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | private static void readFileUsingBufferedReader(String filePath) { try(BufferedReader br = new BufferedReader(new FileReader(filePath))) { String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } |
2- Scanner
Another common way is to wrap FileReader with a Scanner object. This technique is also efficient for reading large text files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | private static void readFileUsingScanner(String filePath) { try(Scanner in = new Scanner(new FileReader(filePath))) { while(in.hasNext()) { String line = in.nextLine(); System.out.println(line); } } catch (FileNotFoundException e) { e.printStackTrace(); } } |
3- Java nio
Using the nio package which is introduced in JDK 7, we can store a whole plain text file into a List<String> using Files.readAllLines(). It is clear that this method is not efficient for reading large text files as it loads the whole file into the memory which can cause memory leaks in case of huge files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | private static void readFileUsingFiles(String filePath) { Path path = Paths.get(filePath); try { List<String> lines = Files.readAllLines(path); for(String line : lines) { System.out.println(line); } } catch(IOException ex) { ex.printStackTrace(); } } |
4- Java 8
With Java 8, you can store the contents of a text file to List<String> using one line as the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | private static void readFileJava8(String filePath) { Path path = Paths.get(filePath); try { List<String> lines = Files.lines(path).collect(Collectors.toList()); for(String line : lines) { System.out.println(line); } } catch(Exception ex) { ex.printStackTrace(); } } |
Again, this technique is commonly used for reading small to midrange text files as it loads the whole file contents into the memory.