Friday, 16 August 2013

How We Can Read File Using Exceptions Through Scanner Class

Exception handling is powerful feature that is supported by java.A method catches an exception using a combination of the try and catch keywords.In the given program we used utility package for using scanner class and IO package using various exceptions.A try block can be followed by multiple catch blocks. The syntax for multiple catch blocks looks like the following:


WAP to display the content of file using exceptions through scanner class

import java.util.*;                                 //Using scanner class
import java.io.*;                                  //Using Exceptions
public class msexcep{
public static void main(String args[])
{
File file=new File("D:/data.txt");         //Specify path that you have create text file
try{
Scanner scanner = new Scanner(file);

while(scanner.hasNextLine()){          //hasNext line function used to read text in file
String line=scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
catch(FileNotFoundException n){     //If file not found then this exception executed
n.printStackTrace();

}
catch (NumberFormatException n)     //It shows the content of the file
System.out.println("The file contains non numeric data."); 

}
}
}

Output of this program:


Exception handling


Like the Post? Do share with your Friends.

No comments:

Post a Comment

IconIconIconFollow Me on Pinterest

Blogger news

Blogroll

What's Hot