Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Read Data from File in Java

In this article you will learn how java deals with text files and how we can read text files and display the data on the screen.

Filling is one of the most important topics in domain of learning java; it can be used in many applications where we want to keep records for future use. You will need to create two classes in order to understand this tutorial.

First of all make a new project with any suitable name in our case it is as mentioned below.

  • Pakage: learnFilingInJava
  • First class name: Laptopread
  • Second class name: ReadFromFile

Laptopread is a simple class that contain instance variables constructor and setters and getters methods that will be used to retrieve data from the text file.

Listing 1: Laptopread Class

packagefileDemonstration;
publicclassLaptopread {
	private String name;
	privateint price;
	private String model;
	privatedoubleprocessor;
	
	Laptopread(){
		this ("",0,"",0.0);
	//passing the following values when no argument constructor is called,
	
		
	}
	Laptopread(String n,intp,Stringm,doublepr){
		name=n;
		price = p;
		model = m;
		processor =pr;
		
	}
	voidsetName(String name){
		name=name;
	}
	voidsetPrice(int p){
		price=p;
	}
	voidsetModel(String m){
		model=m;
	}
	voidsetProcessor(doublepr){
		processor=pr;
	}
	
	String getName(){
		return name;
	}
	intgetPrice(){
		return price;
	}
	String getModel(){
	return model;
	}
	doublegetProcessor(){
		returnprocessor;
	}
	
	@Override
	public String toString(){
	returnString.format("Laptop name: "+name+" price : "+price +" model :"+model+" processor :"+processor);
	
	}
	}

Explaination to the code of Listing: 1Laptopread class

The instance variables or the attributes used in this class are:

private String name;
privateint price;
private String model;
private double processor;

These are the attributes of Laptop. This means that the data stored in the laptop.txt files should be in this format.

Dell 65000 inspironn5110 4.3
Hp 55000 hptype 4.2

Now the question arises why?

Coming back to our Laptopread class the next thing is constructor that is used with four arguments.

Laptopread(String n,intp,Stringm,doublepr){
		name=n;
		price = p;
		model = m;
		processor =pr;
		
	}

The next part of the class contains setters and getters method. The setter method can be used to set value to/update a particular attribute of the class Laptopread class. Getters methods are used to return the value of specific attribute.

These methods are very necessary for reading data from the text file .besides this we also have a toString method that has no special use but is apart of class.

Listing 2: ReadFromFile

packagelearnFilingInJava;

importjava.io.File;
importjava.io.FileNotFoundException;
importjava.util.Scanner;

publicclassReadFromFile {

	publicstaticvoid main(String[] args) {
		// TODO Auto-generated method stub
 Scanner in = null;
try{
	in =new Scanner(new File("data.txt"));
 }
catch(FileNotFoundException e)
 {
	e.printStackTrace();
 }
LaptopreadltRec =newLaptopread();
System.out.printf("%s %s %s %s", "laptop name","laptopprice","model","processor");
try{
	while(in.hasNext()){
		ltRec.setName(in.next());
		ltRec.setPrice(in.nextInt());
		ltRec.setModel(in.next());
		ltRec.setProcessor(in.nextDouble());
		
		System.out.printf("%s %d %s %f", ltRec.getName(),ltRec.getPrice(),ltRec.getModel(),ltRec.getProcessor());
	 }
	
	
 }
catch (Exception e) {
		e.printStackTrace();
	}
	
in.close();
	}

}

Explanation to code of Listing 2: ReadFromFile class:

Now here our main topic discussion starts, that is how to read data from the file. Looking at the ReadFromFile class we have:

Scanner in = null;

That is used usually to take input from the user using key board, but here we will use file as our input medium.

Next line of code is:


try{
	in =new Scanner(new File("data.txt"));
 }
catch(FileNotFoundException e)
{ //catch blocks catch if the FileNotFoundException occurred 
// and prints stack trace 
	e.printStackTrace();
	// will show the stack trace of exception occurrence.
 }

Here we have passed our new File object (which takes data.txt) as an argument to the object of Scanner class. We can use the in reference to set instances of class by taking inputs from the file and can be shown easily on the screen.

Note: we have used different try and catch blocks to control different types of exceptions related to files.

Next lines of code is:

LaptopreadltRec =newLaptopread();

Now creating the object of Laptopread class and in the next line we just print the heading what is being read from the file as you will see in the figure which shows you the data read from the file.

Let’s look at the next lines of code:

try{
	while(in.hasNext()){
		ltRec.setName(in.next());
		ltRec.setPrice(in.nextInt());
		ltRec.setModel(in.next());
		ltRec.setProcessor(in.nextDouble());
		
		System.out.printf("%s %d %s %f", ltRec.getName(),ltRec.getPrice(),ltRec.getModel(),ltRec.getProcessor());
	 }
	
	
 }
catch (Exception e) {
		e.printStackTrace();
	}

Within try block we start a while loop which we continue until the end of file is reached. In java the end of file indication is given by the Operating system. So don’t think about how they handle it but just stick with the code. Now we call different set methods of ItRec objects and starts reading data from the file with appropriate data types given to appropriate instance ItRecobject.

After that using getter method we display the data on the screen. Once again we have used try and catch blocks to handle exceptions. At the end of program we need to close the file by calling the close() method of in object , as shown below.

in.close();
showing Result of program

Figure 1: Showing Result of program

Conclusion

So in this article you learned how we can read data from the text files in java , but reading from the text files is little tedious work, because you must now what type of data you want to read. Besides text files we can also read data and write data to binary file.



computer science Graduate :Ceo at www.gigsclerk.com (Best Marketplace to Buy and sell service online from 2$-100$ ) and www.trustingeeks.com. Interested in programming, online buissiness. Android development.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login