How to use FileNotFoundException in Java

The ReadFile achieves the functionality by testing for a FileNotFoundException using try catch statements.

ReadFile

import java.io.*;

public class ReadFile
{

public static void main(String[] args) throws
IOException
{
File inputFile = new File(''File1.txt");
Try
{
FileReader in = new FileReader(inputFile);
int c;
while ((c = in.read()) != -1)
{
System.out.print( (char) c );
}
in.close();
}
catch (FileNotFoundException e)
{
System.out.println("File does not exist");
System.exit(1);
}
}
}



Most of the program's processing is within the try statement. In line 9, if the file File1.txt does not physically exist, then the java.io.FileReader constructor will raise a FileNotFoundException. This exception is handled by the catch statement

in line 15. In this case, the program prints a message, then terminates using the
System.exit method (lines 16–17).

No comments:

Post a Comment