How to Read a Text File in Java
Did we not just learn how to take input from user in Java in the last chapter? It would be only befitting to learn how to read a text file in Java almost immediately.
Why, you ask? You see, that’s how the world rolls out there. There would be plenty of occasions wherein you will find people asking you to grab inputs from a file, and not manually enter them via console or parameters like we learned. As complexities in your life increase, you have to learn to deal with generic scenarios instead of the specific ones. That’s how you become a badass coder too.
So without wasting any more time let’s learn how to read a text file in Java.
Things you need for Learning How to Read a Text File in Java
I am guessing you have been following the Jedi path so far to learn Java from the tutorials I made you. So, we have already created a project, a package and a class in our Eclipse IDE, and are ready to shoot right away.
The next thing you need would be, of course, a text file with something in it.
There!
We have one now. I know, this GOT obsession has got to go.
Save the file.
It’s time to learn about the ways to read your file. Depending upon the type of stuff your file’s got there are different ways to read em.
The ways we are going to look at here are:
- FileReader Class
- FileInputStream Class
- Scanner Class
- Files and Paths
Pah! So many ways to do one thing. Isn’t that kind of exhausting?
But it’s your pick after all. My job’s to spread awareness.
FileReader Class
FileReader is one of those classes that can be used to read text files. However, you gotta use the class BufferedReader in order to exploit its readLine capabilities primarily because if you try to use the read method of FileReader to read your text file, you will only get it in the form of int.
BufferedReader will be able to read through your text file, and print the same as is after extracting the info in bytes from FileReader.
So we are going to use the infamous:
BufferedReader br = new BufferedReader( new FileReader ("pathname"));
Yes that’s exactly what we used in the previous chapter sans the pathname bit to extract inputs.
Here you just have to replace the “pathname” with the location of your file, and the name of the file, of course.
Steps to Learn How to Read a Text File in Java
So here’s our first step:
Step 1: Since we are dealing with input output classes and methods, it’s only reasonable to use the “import java.io.*” clause in the beginning of our Java file.
Step 2: Add the aforementioned BufferedReader cum FileReader code to our waiting main method. With that our code’s gonna look something like this:
Step 3: Now Java doesn’t understand if ‘\’ is meant to separate folders, so in order to make it understand replace ‘\’ with ‘\\’.
Now that’s not the only error Eclipse flings at you at this stage. If you notice the red button towards the left, and place your cursor there you will see an exception is supposed to be handled. What exception is that? It is the File not found exception.
What if your code tries to look for the file in the aforesaid path, and it doesn’t find that exact file lurking there? What would happen then. We need to handle that situation. It takes us to our next step.
Step 4: Append “throws FileNotFoundException” to your main method.
Moving on.
Step 5: Call readLine() method using the ‘br’ object we created for BufferedReader, and since it returns String assign it to a String variable ‘s’.
Another Exception
Hey there’s another red error bulb lighting our doorway. What could that be?
Alright so readLine requires you to handle yet another exception called IOException. We are familiar with this right?
Step 6: Append “IOException” to tackle this. You can simply use an additional comma to separate the previous one with this. That’s us trying to do what Java expects of us.
Alright so that red danger button’s gone. Bulb’s fine. It means warning.
Step 7: We will try to display what ‘s’ has bagged via readLine(). To do that we will make use of System.out.println:
We might choose to use BufferedReader’s close() method to ace good coding practice.
Step 8: Proceed to run this by clicking on the green arrow button.
See?
There’s your Jon Snow with the low IQ!
With that we just read a file and whatever input it had.
FileInputStream Class
You can never overlook the FileInputStream Class when it comes to figuring out how to read a text file in Java. You can make use of FileInputStream Class as well when there are bizarre characters in your text file. It is primarily very useful for binary data.
All you have to do is simply declare FileInputStream Class the way you did it for every class so far.
Step 1: Add the code
FileInputStream fis = new FileInputStream (path);
replacing the path name with the location and name of your file.
Things look the same so far, and appear to be going in the same direction henceforth. It is only that we don’t have a great reading method for FileInputStream. There is one that returns int which as a matter of fact our file doesn’t retain. Then there is the one that we will have to make do wtih:
read(byte[] b)
with the return type as Int. I know this looks weird to you if you are looking at it first time. It is a byte type array inside the parenthesis.
Working with Arrays
We will learn how to work with arrays in the upcoming chapters, and we will have fun with it too. For now just remember this is how we define an array:
return_type[] variable = new return_type[size];
where size can be replaced with the no. of slots you wish to retain.
So since here we are dealing with byte as the return type, our array declaration would look something like this:
byte[] buffer = new byte[30];
With that we will jump to the next step.
Step 2: Declare an array called buffer that will act as a storehouse for our characters for now. It would be only apt to call it a buffer.
Step 3: Now it will be only fair to use the read method of our FileInputStream class to call the stuff into our buffer array. With the addition of this particular line all that we have garnered from our file goes into the array slots.
Step 4: Now since buffer has been defined as byte. If you choose to print buffer directly using System.out.println you will get some out of the world surreal data. Go ahead and check. I dare you.
Remember this is all the data in byte format. We have to set things straight by converting it into String format.
In order to convert byte[] into a String you need to explicitly create a String object and pass the byte array as a parameter. We will replace the parameter with the already populated buffer array.
Step 5: Replace the ‘buffer’ in the last step with ‘new String(buffer)’. That’s it, and run the program:
And Jon Snow still doesn’t know anything. I thought he might have got some clue by now.
Scanner Class
Since we learnt about this a chapter ago, I think it would be only fair to know that it is capable of reading even text files, and not just System.in keyboard stuff. I think Scanner plays a vital role in figuring out how to read a text file in Java.
The reason I placed this third is owing to the usage of while loop here. I intend to cover loops in the upcoming chapters where I promise we will have some fun too. Will do plenty of examples to get a hang of how loops work.
Here’s just a glimpse of one of the most useful loops present in programming. It’s called the while loop.
The syntax to remember here is:
while(condition) { -------------do something----------- }
Simply replace the condition that needs to be satisfied in order to enter the braces. Whatever goes in the “do something” section will be performed as long as the condition is met. The moment the condition part fails it will exit the loop. The rest of the code will follow the way it generally does.
Steps to Use Scanner Class to Read Input from a File
So, here we are with the Scanner class.
The first step would be to declare it like we had learnt only here we are going to make use of File class to grab the file name from its path.
Scanner scan = new Scanner(new File(pathname));
Step 1: Time to import java.util.Scanner; since Scanner requires that.
Step 2: Use the above code to declare Scanner.
Remember to use the File class since Scanner is incapable of identifying it as a path location.
Step 3: Time to use the while loop. There is this method of Scanner called hasNextLine() that returns value in boolean. Boolean return types are great when you are messing with conditions in loops.
It means it will keep searching till there are no more lines to scour through. Of course you can use any version of a condition here. I am just giving you an instance.
Step 4: Time to bring the cavalry in. Make use of the nextLine() method to bag the String there is in your file. Print it and you are good to go.
Jon Snow is just terrible with knowledge.
The Neat and Modern Method using Files and Paths Classes
We haven’t finished learning how to read a text file in Java just yet.
Let me drop the A-bomb on you. It’s not the preferred way nowadays. Java is evolving. The latest version of Java is all about using concise things to get Herculean jobs done within split seconds. It means lesser coding mess.
With that there comes yet another method to tackle this “how to read a text file in Java” situation.
NIO Files
There are these nio.file.Files and nio.file.Paths classes that you have to use that are going to get the job done in a single line of code.
Step 1: Add the following code at the top:
import java.nio.file.*;
This will import both the classes Files and Paths allowing you to use their methods.
Step 2: Type the following code in your main method:
String s = new String(Files.readAllBytes(Paths.get(path));
Make sure you replace the ‘path’ keyword with your actual file path.
I will explain here what’s happening.
You are basically using the readAllBytes method of the Files class to get whatever is there in your file in the Bytes format. Now remember how we changed everything to String to avoid getting weird data? That’s what we did by using the new String(bytes) Class.
Paths.get(path) is nothing but a way to grab where your file is. It’s then used by Files class to read every bit.
Step 3: Now since we have assigned all our data in String format to the variable ‘s’ it’s time to show it.
How do we do that? Boy! was that a feeble shout.
Using System.out.println to display ‘s’:
There! This guy has to be the dumbest person on Earth.
Alright peeps hope you have enjoyed learning how to read a text file in Java, hope to see you with a chapter on writing stuff on a file pretty soon.
Till then Sayonara!