In this article, you will learn about different ways to use Java to read the contents of a file line-by-line. This article uses methods from the following Java classes: java.io.BufferedReader
, java.util.Scanner
, Files.readAllLines()
, and java.io.RandomAccessFile
.
BufferedReader
You can use the readLine()
method from java.io.BufferedReader
to read a file line-by-line to String. This method returns null
when the end of the file is reached.
Here is an example program to read a file line-by-line with BufferedReader
:
Continue your learning with the BufferedReader
API Doc (Java SE 8).
Scanner
You can use the Scanner
class to open a file and then read its content line-by-line.
Here is an example program to read a file line-by-line with Scanner
:
Continue your learning with the Scanner
API Doc (Java SE 8).
Files
java.nio.file.Files
is a utility class that contains various useful methods. The readAllLines()
method can be used to read all the file lines into a list of strings.
Here is an example program to read a file line-by-line with Files
:
Continue your learning with the Files
API Doc (Java SE 8).
RandomAccessFile
You can use RandomAccessFile
to open a file in read mode and then use its readLine
method to read a file line-by-line.
Here is an example program to read a file line-by-line with RandomAccessFile
:
Continue your learning with the RandomAccessFile
API Doc (Java SE 8).
If a file is stored in an encoding other than UTF-8, you should specify the correct encoding when reading it.
UTF-8
EncodingFileChannel
For massive files (GB-sized logs or datasets), Java’s NIO API (FileChannel
) is a high-performance alternative to standard file reading.
Here is an example:
Using FileChannel
significantly reduces memory usage compared to loading a file into memory at once.
For more advanced file handling techniques, you can check out this tutorial on Java Files - java.nio.file.Files Class.
FileReader
?To read a file in Java using FileReader
, you can create an instance of FileReader
and read character data from the file. However, FileReader
is not the most efficient option as it does not buffer the input. A better alternative is to wrap it inside a BufferedReader
.
For more efficient file reading, consider using BufferedReader instead.
The most common way to read a file line by line in Java is by using BufferedReader
. This method is memory-efficient and performs well for large files.
Example using BufferedReader
:
For additional file handling methods, check out this tutorial on Java File Handling.
When dealing with large files, reading the entire file into memory is inefficient. Instead, use streams or Java NIO (Non-blocking I/O) APIs like FileChannel
for better performance.
FileChannel
(Best for Extremely Large Files)For extremely large files, consider memory-mapped files or FileChannel
for improved performance as described in the section above.
Error handling is crucial to avoid crashes due to file not found, permissions issues, or encoding mismatches.
Files.exists(Path.of("file.txt"))
.IOException
to handle errors gracefully.FileReader
and BufferedReader
?Feature | FileReader | BufferedReader |
---|---|---|
Performance | Reads one character at a time | Reads a full buffer (default 8192 bytes) at a time |
Use case | Small files, simple character-based reading | Efficient reading, best for large files |
Efficiency | Less efficient | Highly efficient |
To handle large text files efficiently, always prefer BufferedReader
over FileReader
. Learn more about efficient file operations in tutorial on Java read text file.
In this comprehensive guide, you learned various methods to read the contents of a file line-by-line in Java, including the use of BufferedReader
, Scanner
, Files.readAllLines()
, and RandomAccessFile
. You also learned how to handle file reading errors, the difference between FileReader
and BufferedReader
, and how to efficiently handle large files using FileChannel
or memory-mapped files.
Continue your learning with more Java tutorials.
You can also refer to these tutorials on:
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Looks very good. Would you be so kind to give an example on how to read random lines from a file?
- Vulco Viljoen
Hello I have to create java program in such a way that output should be print on thermal printer for which paper size ,font size etc should be modified with text file ( template )…I have created program which read normal file and print but how to handle paper size anf font size things pls help me out there
- Rinku
I want to create a java program to read input from text file but don’t want to read all the lines at once,Instead I want my Java program to read Input as in when required line by line. need help… Thanks a lot , for giving a shot to my query.
- Dinesh
Thanks for your tutorials. Is there a way to grab each individual line and assign it to a variable? Somthing like String line [ i } = reader.readLine(); String line1 = line[ o ]; String line2 = line [1 ]; and so on. I tried this and I get the first line on the first line1 string with the rest as nulls. Then i get the first and second line with the rest as nulls on line2 string.
- Bill Melendez
I write a file handling program, I read data from file. In a file a create a table(name,age,clg) when I read data,I get data with column name but I want only data nat file name please suggest me how can do
- Sp
Is there a way to read a specific line from a file without first reading all previous lines if you know the line length? I’m seeking something analogous to the BASIC code OPEN FILE$ AS 1 LEN = 5 READ #1, 5, LINE% READ #1, LINE%, DESC$
- Jeff Mullen
SO what im trying to do is reading each line from a file (named fileName) and writing it into a new file (named fileName2), so basically a copier. How would you do that?
- Ana Pathak