Read contents of a file line by line in Java
This post will discuss how to read the contents of a file line by line in Java.
There are several ways to read the contents of a file line by line in Java using BufferedReader, Files, Scanner, and RandomAccessFile class, and third-party libraries such as Guava and Apache Commons IO. These are discussed below in detail:
1. Using BufferedReader class
BufferedReader is a class that provides buffered reading of characters from a stream. It can wrap around any Reader object, such as FileReader, InputStreamReader, or StringReader, and read characters from it efficiently. BufferedReader has a method called readLine() that returns a String containing the contents of a line from the stream, or null if the end of the stream has been reached. To use BufferedReader to read a file line by line, we can do:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; class Main { public static void main(String[] args) { File file = new File("demo.txt"); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line; while ((line = br.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } } } |
The BufferedReader provides efficient reading of large files by buffering the characters in memory. In Java 8 and above, we can use the BufferedReader.lines() method to get a stream of lines of text read from BufferedReader. This is demonstrated below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; class Main { public static void main(String[] args) { File file = new File("demo.txt"); try { BufferedReader reader = new BufferedReader(new FileReader(file)); reader.lines().forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } } |
2. Using Files class
Files is a utility class that provides various methods for working with files and directories. The Files class provides a convenient and concise method readAllLines() to read all the lines from a file into a List of Strings. It can also take a Charset argument to specify the character encoding of the file. Here is an example of using the Files to read a file line by line:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { Path path = Paths.get("demo.txt"); try { List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8); lines.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } } |
Java 8 introduced lines() method in the Files class, which can read all lines from a file as a stream. It takes the path to the file and overloaded it to accept the charset for decoding.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.stream.Stream; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { Path path = Paths.get("demo.txt"); try (Stream<String> stream = Files.lines(path, StandardCharsets.UTF_8)) { stream.forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } } |
3. Using Scanner class
Another plausible way of reading a file in Java is to construct a Scanner that produces values scanned from the specified file. The Scanner class provides convenient methods for reading input from various sources. It has a method called hasNextLine() that returns true if there is another line in the input, and a method called nextLine() that returns the next line from the input. We can use Scanner to read a file line by line as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
import java.io.File; import java.io.IOException; import java.util.Scanner; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { File file = new File("demo.txt"); try (Scanner sc = new Scanner(file, StandardCharsets.UTF_8)) { while (sc.hasNextLine()) { System.out.println(sc.nextLine()); } } catch (IOException e) { e.printStackTrace(); } } } |
The Scanner can read input from various sources, such as keyboard, files, streams, or strings and parse different types of data. However, it may be slower than BufferedReader, as it performs more operations on the input, such as parsing and tokenizing.
4. Using RandomAccessFile class
RandomAccessFile is a class that allows reading and writing data from any position in a file. It can be used to access files in a random-access manner, rather than sequentially. RandomAccessFile has a method called readLine() that reads the next line of text from the file. It returns null if the end of the file has been reached. Here is an example of using the RandomAccessFile to read a file line by line:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.io.IOException; import java.io.RandomAccessFile; class Main { public static void main(String[] args) { String fileName = "demo.txt"; try (RandomAccessFile raf = new RandomAccessFile(fileName, "r")) { String line = raf.readLine(); while (line != null) { System.out.println(line); line = raf.readLine(); } } catch (IOException e) { e.printStackTrace(); } } } |
The RandomAccessFile supports different modes of operation and allows random access to any position in a file. However, it may be more complex and error-prone than the other methods, as it requires handling low-level details such as byte arrays, character encodings, and file pointers.
5. Using Guava Library
Guava Files class provides several utility methods for working with files. We can use the Files.readLines() method that reads all the lines from a file into a mutable list. It accepts two parameters: the file to read from and the charset used to decode the input stream. It throws an IOException if an I/O error occurs. To get an immutable list, we can use Files.asCharSource(file, charset).readLines() method instead. Here is an example of using the Files.readLines() method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import com.google.common.io.Files; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { File file = new File("demo.txt"); try { Files.readLines(file, StandardCharsets.UTF_8) .forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } } |
6. Using Apache Commons IO
The Apache commons IO provides an utility method called FileUtils.readLines() that allows us to read the contents of a file line by line into a list of strings. It takes two parameters: a File object representing the file to read, and a String object representing the encoding to use. Here is an example of using the FileUtils.readLines() method:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import org.apache.commons.io.FileUtils; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; class Main { public static void main(String[] args) { File file = new File("demo.txt"); try { FileUtils.readLines(file, StandardCharsets.UTF_8) .forEach(System.out::println); } catch (IOException e) { e.printStackTrace(); } } } |
That’s all about reading the contents of a file line by line in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)