DEV Community

loading...
Cover image for How to read from file in java?

How to read from file in java?

joshuabrown0010 profile image joshua-brown0010 ・3 min read

In this article, I am going to make you learn how to read stuff from a file in java. This is simple to learn and I have placed three files for your reference.

Approach

  • So as you can already see I have created this Indian.txt file and I added three more records to it, you can see in the below file. So it has four records and a record is pretty much a row of data. So now let's go ahead and figure out. As we don't know how to access it from a Java program so that's what I'm going to be explaining you today.
  • We can use scanner object to read from our keyboard using system.in but we can actually use scanner to read from a file as well so let's go ahead and first make a private scanner variable.
  • So name scanner and just make a method to open the file first. So public void open file () and put try to open the file so set scanner variable and again put a new scanner just put new file and place Indian.text.
  • Instead of reading from your keyboard it's actually going to read from this Indian.text file and if we get any errors place catch those errors exceptions e and print something like good nods fine file looks good enough so now we have a method to open the file easy enough
  • Make a method to read the data from that file so public void just name it like read a file. The next thing we want to do is create a while loop, and put your file name which is X with hasNext() which is a built in method.
  • Now each of these records has an ID number a first name and a last name in Indians.text file, so we're going to want three variables to hold those string a and let's go ahead and copy that actually we're going to put string = x .next(); and this is going to be b and c.
  • It going to assign 20 equal to a then it's going to assign Buckey equal to B and Roberts equal to C and then print those out so system.out.printf, and print just three string variables are going to print it out.
  • It's going to keep printing those out until it gets to the end of the file and then it's going to break out that while loop. So that's actually the only thing we need in this read file method. So now we just need that one last method and what this is going to do is close the file
  • All we want this to do is close that file X and now looks like we got everything. Check for errors.
  • Now start putting it in our main and put read file and now let's go ahead and put our open file r dot read file and r dot close file right there.
  • To open it read the stuff from it and close it when we're done with it. So now let's go ahead
  • and run this and we'll see what we got. We have got pretty much exactly what is in our text file. It just printed all this out it stored. It got three new variables store this in a b c print out and the file and a broke out. Read more

Discussion (0)

pic
Editor guide