As simple as this may seem to experienced Java programmers, I still see many posts in the Java Forums from beginners asking this very question: How do you read a text file line-by-line using a BufferedReader? Let’s find out.
Suppose we have a text file called input.txt. This text file contains an arbitrary length of lines (be it words, numbers, or whatever). You are required to read in this text file line-by-line. How do we do it?
First thing: Create a text file to use for testing, and name it input.txt. Save this text file in the root of your project folder. For now, let’s make this text file simple:
Line 1
Line 2
Line 3
Line 4
Now we have to read it in. For this, we will need at least a BufferedReader. There are other ways to do this (Scanner, for example), but we will only be explaining this way. We also need a FileReader since we are reading input from a file.
Now let’s take a look at the code…
The Code
Since this post is aimed towards beginners, I will do my best to explain each line of code.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BReader {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader( new FileReader("input.txt") );
String line;
while ( ( line = in.readLine() ) != null ) {
System.out.println( line );
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation
In the following block of code, we need to import several classes: BufferedReader, FileReader, and IOException. We use the BufferedReader class in conunction with the FileReader to read in the file’s text. We import IOException because performing this action can throw an IOException, and if it does, we want to catch it and display the error message.
import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException;
In the following block of code, line 5 starts the class which we named BReader. Conversely, the file name is called BReader.java. In line 7, we start the main method, which is called when the program runs.
public class BReader {
public static void main(String[] args) {
In the next block, we do the actual reading. Line 10 opens up the try block, which “catches” any errors and prints them out in lines 23-27. In line 12, we open the input.txt file and set up a BufferedReader so we can read the file line-by-line. In line 13, we create a new String called line which we use to store each line that we read in.
Line 15 may be the trickiest to understand, because we actually use an assignment within parentheses and then check if the variable is not null after the assignment — all in one line. So we are saying: while line gets in.readLine() does not equal to null, do something. There are other ways to do this, for example, by calling the readLine() method within the while loop, but the previous method is the one I prefer. The reason we are checking if the line is null, is because at the end of the file when we try to read a line that isn’t there, we will be returned a null, indicating that we should stop reading (because the condition no longer satisfies the while loop).
Within the while loop on line 17, we are simply printing the line. After that, we close the while loop bracket, and on line 21 we close the input.
The next part of the code was already explained, but just to reiterate: On lines 23-27, we have the catch block which we use to print out any errors / exceptions that have occurred. These will be printed out to the console, should anything happen (e.g. file not found). Following this, we close the bracket to the try / catch block, the main method, and then the class.
try {
BufferedReader in = new BufferedReader( new FileReader("input.txt") );
String line;
while ( ( line = in.readLine() ) != null ) {
System.out.println( line );
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Questions, comments? Let me know below.
Tags: BufferedReader, read, text file

September 7th, 2009 at 9:20 pm
What if i wanted to read a specific line? like what if i didnt just want to read all lines of the entire file, what if i only wanted to read line… 250? is there a way to do this without just a line counter and an if line = 250? perhaps another method? any advice would be welcome.
September 7th, 2009 at 9:50 pm
Hello,
Thanks for your comment! This might not be what you want to hear, but I would do precisely what you don’t want to do. I’d read the input line-by-line using a stream and only do something when your condition is true (if we’re using your example, this would be when you reach line number 250). You can do this by using a while or for loop. Unfortunately there is no other way that I know of to read, say, line 250 of a file without having already read up to line 250. Otherwise, how do you know that the file even has a line 250 in it? The API certainly doesn’t provide a method like this, and logically, I can’t think of a good way to accomplish this. But that’s really besides the point. The point is, why do you need to do this?
Are you having some sort of performance issue with using this method? If so, how did you measure it? Keeping with the example you gave, reading only 250 lines of a file should take milliseconds. What may slow this process down is if you’re storing the lines in memory unnecessarily.
Please feel free to post back with more details and I’ll be glad to help
September 7th, 2009 at 10:17 pm
It’s a dumb class project. The basic idea of it is that phone numbers can be turned into words for better memory. So like phone number 825-3688 could be advertized as “Take out”. So I wrote an algorithm that will turn any phone number into every permutation of possible letters and output it to a file. Then I found a basic lexicon online my program cross references the file of letter permutations with the list of real words to root out entries that don’t make sense. So it would accept “take out”, but reject “xto zitp”. The problem is basically that because of how the algorithm works, there are multiples of each substring. That probably made no sense. Basically there would be “Take out”, but there is also “Take nvv” and “Take mvp” etc. I could do it that it will read all the lines and only take every 25th or whatever, but for general ease and personal curiosity I wanted to do some lineRead(int line). Too bad it doesn’t exist. Woulda been nice.
September 7th, 2009 at 10:38 pm
How so? Storing “825-3668″ as “Take out” has the same number of characters. If you left it alone, then you wouldn’t need to figure out what the number is, since more than one letter is shared for different numbers (this is the problem, right?).
Unless your instructor WANTS you to do this, that is… Otherwise I would change the premise of the idea and just store the phone number as a String without translating it to text.
September 7th, 2009 at 10:44 pm
I just realized you probably meant memory as in your ability to remember the number — not computer memory
September 7th, 2009 at 10:46 pm
ah no. i don’t mean computer memory, i mean person memory. so like how on a phone each number corresponds to 3 letters, so that if like you own a liquor store and your phone number was 233-7226, it would be nice to know that on a phone, dialing 233-7226 is the same as Beer can. so then on a commercial for your store, you could say just call (816)-Beer-Can and people would remember your store’s number better.
sorry for the confusion on that
September 7th, 2009 at 11:18 pm
I get what you’re doing, and it’s not an inherently easy problem to solve. Though from your description, I don’t see how this is related to reading a specified line from a file. But like I mentioned, the only way to do this that I know of is to read line-by-line. If you explain a little more into detail about what you’re reading in or post an example of what you’re doing, that would help.
July 22nd, 2010 at 8:49 pm
I have two answers, both involve use Random access file (search for RandomAccessFile)
http://download.oracle.com/docs/cd/E17476_01/javase/1.4.2/docs/api/java/io/RandomAccessFile.html
Random access files permit nonsequential, or random, access to a file’s contents. To access a file randomly, you open the file, seek a particular location, and read from or write to that file.
Technique #1 use fixed length lines, add spaces to each line so they are all 20 bytes long. Then position in the file is pos = lineNumber * 20; RandAccessFile.seek(pos); read(byteArrayOf20);
Technique #2 Make an index of your file. Read the entire file one time and store an array (the index) like this: { 0, 20, 45 }. Then to get super fast access to specific lines in the file, just cross reference using the array: Line 0 starts at position 0 (always!), line 1 starts at position 20, line 3 starts at position 45.
randAccessFile.scan(posIndex[lineNum]) ; read(…);
Both of these methods are used in database software like MySQL.