Java io filenotfoundexception example

FileNotFoundException in Java Exception Handling And Resolution Example

FileNotFoundException In Java: In this article, we’re going to talk about a very common exception in Java – the FileNotFoundException. we can get this exception when we try to access the file but the file is not present in that location,

Possible Reasons For FileNotFound Exception

There are a few possible reasons for getting this type of exception, here are some:

  • A File may be present or not in the mentioned path
  • A file with the specified pathname does exist but is inaccessible for some reason (requested writing for a read-only file, or permissions don’t allow accessing the file)

FileNotFoundException in Java

This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing.

Читайте также:  How to link javascript to html
Check Also: Scientific Games Interview Questions

we will get this exception when we are trying to access a file that does not exist. for access to the files, we are using classes like FileInputStream, FileOutputStream, and RandomAccessFile. The main function of these classes is used to obtain the bytes from a file system.

package co.java.exception; import java.io.File; import java.io.FileReader; public class FileNotFoundException < @SuppressWarnings("unused") public static void main(String[] args) throws java.io.FileNotFoundException < File file = new File("E://file.txt"); @SuppressWarnings("resource") FileReader fr = new FileReader(file); >>

Let’s Run the above program

After execution we get an error:

Exception in thread "main" java.io.FileNotFoundException: E:\file.txt (The system cannot find the file specified) at java.io.FileInputStream.open0(Native Method) at java.io.FileInputStream.open(Unknown Source) at java.io.FileInputStream.<init>(Unknown Source) at java.io.FileReader.<init>(Unknown Source) at co.java.exception.FileNotFoundException.main(FileNotFoundException.java:12)

How to Deal FileNotFound Exception

  • Once you got this exception than the first thing you need to check the path which you mentioned in your program to verify that the specified file is present or not in the mentioned path.
  • if the file is present in the specified location but still you got the error then you need to check error message for confirming is there any mention about permission related issues if there are some permission related issues then you need to fix that issue or you need to verify that file is used by other application or not.
  • Alert a user with a dialogue or error message: this isn’t a stop execution error, so just notifying is enough
  • Just log an error: this error should not stop the execution but you log it for future analysis
Читайте также:  Primitive types in kotlin

in this post, we’ve seen when a FileNotFoundException can occur and several options to handle it. if still, you have any doubts then feel free to drop your question in the comment section.

Источник

Java FileNotFoundException

Java FileNotFoundException

Java FileNotFoundException is a type of exception that often occurs while working with File APIs in Java where the path specified for a file for reading or writing purposes in the constructor of classes FileInputStream, FileOutputStream, and RandomAccessFile, either does not exist or inaccessible due to an existing lock or other technical issues. This is a checked exception is a direct subclass of IOException that has been introduced with JDK 1.0. Also, it contains two types of constructors that can be called where one returns an Exception with a null message to display, whereas the other prints the specified message in case the exception occurs.

Web development, programming languages, Software testing & others

public class FileNotFoundExceptionextends IOException
  • public: The keyword public refers to that the given class is accessible from any class in the project and needs to be inherited to throw an exception.

This class is a direct subclass of IOException, thus inheriting all the class’s methods and variables.

How FileNotFoundException work in Java?

FileNotFoundException is a checked exception is used that occurs when a file path specified for accessing does not exist or is inaccessible. With the checked exception, it means that the java compiler checks at compile time if this exception has been handled or not; otherwise, a compile-time error occurs. Let us see how the exception is thrown at run-time in case it has been handled using try-catch blocks or using throws keyword in its definition at compiler time.

File fileObj = new File("C:/JavaPractice.txt")

Suppose we instantiate a File class object as given above with a path of a file, and that file does not exist. In that case, when the compiler attempts to read or write the file and finds such a situation, it throws an exception and create an instance of FileNotFoundExceptionclass. In case it is not specified which constructor needs to be called, the constructor with no error message is thrown.

Thus the application fails with the below error:

Java FileNotFoundException 1

Constructors of Java FileNotFoundException

FileNotFoundException is a subclass of IOException that is very useful to trace if the file specified in the file path exists and even accessible. Thus for using this, one needs to instantiate it, and it is a public class; it can be instantiated from any where in the project. And for creating the instance of the class has 2 types of constructors.

Given below are the two types of constructors:

1. Constructor with no error message

This type of constructor is used to create an instance of FileNotFoundException class where it returns null as its error detail message.

public FileNotFoundException()
FileNotFoundExceptionexcepObj = new FileNotFoundException()

2. Constructor with an error message

This type of constructor is used to create an instance of FileNotFoundException class where it returns a specified string as its error detail message.

public FileNotFoundException(String s)
FileNotFoundExceptionexcepObj = new FileNotFoundException("This is a FileNotFoundException")

The error message specified can be easily retrieved using the Throwable.getMessage() method since this is one of the superclasses of FileNotFoundException class.

Examples of Java FileNotFoundException

Given below are the examples mentioned:

Example #1

Here we see how an exception is thrown by JVM if one file in inaccessible. In this, the error message displaying in output is one specified by default by JVM.

//package Proc; import java.io.Console; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; public class prac1 < public static void main(String[] args) < File fileObj = new File("D:/JavaPractice.txt"); FileInputStream fISObj = null; try< fISObj = new FileInputStream(fileObj); while (fISObj.read()!=-1)< System.out.println(fISObj.read()); >>catch (FileNotFoundException e)< e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >> >

specified by default by JVM.

Example #2

In this example, we will use the constructor with a specified error message to display the error when the file does not exist at the given path. We have used the throw keyword to throw the exception.

//package Proc; import java.io.Console; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintWriter; public class prac1 < public static void main(String[] args) throws FileNotFoundException,IOException< File fileObj = new File("D:/JavaPractice.txt"); if(!fileObj.exists())< throw new FileNotFoundException("This file doesnot exist in the path specified "+fileObj.toString()); >else < System.out.println("Welcome, we got into file "+fileObj.toString()); >> >

use the constructor with specified error message

How to avoid FileNotFoundException?

Getting a FileNotFoundException in an application makes an application inefficient. The first step to avoid this exception is to check if the specified file exists in at the specified path, but still, there might occur a situation in real-time applications that the file is missing or if other processes lock the file to be read to write into it.

Case 1: File is missing

To avoid this, one can use the java.io.File.exists() method to check if the file one attempts to read exist on the path specified or not. Using this, we must make sure if our code is able to handle the FileNotFoundException exception.

Case 2: File is inaccessible

To avoid such cases, one needs to take care if the file we are attempting to read is currently locked by other users writing it. For this we can use canRead() or canWrite() methods of java.io. File class that tells if the specified file is available for reading or writing purposes or not.

Using these 2 precautionary measures, one can easily avoid an attempt by an instance of file class to open a file that can result into a checked exception. This improves the efficiency of an application that includes a program to access files from a specified path.

Conclusion

FileNotFoundException is a type of checked exception that occurs once an attempt is made to the file that either does not exist or not accessible at that moment due to some lock. Since it is a checked exception java compiler ensures it has been handled at compile time. But still, if one needs to avoid it so they can use exist(), canRead() or canWrite() methods present in File class.

This is a guide to Java FileNotFoundException. Here we discuss how FileNotFoundException work in Java along with the constructors and programming examples. You may also have a look at the following articles to learn more –

89+ Hours of HD Videos
13 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

97+ Hours of HD Videos
15 Courses
12 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5

JAVA Course Bundle — 78 Courses in 1 | 15 Mock Tests
416+ Hours of HD Videos
78 Courses
15 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.8

Источник

java.io.FileNotFoundException (Access is denied) – Causes and Fix

java.io.FileNotFoundException (Access is denied) – Causes and Fix tutorial shows what are the possible causes and fix for java.io.FileNotFoundException (Access is denied) exception.

How to fix java.io.FileNotFoundException (Access is denied) exception?

There are several possible causes due to which you may encounter java.io.FileNotFoundException (Access is denied) exception as given below.

1) Trying to open and read a directory

You cannot open and read a directory like normal files. Trying to do that will result in the exception. Please see the below-given code example where I try to open a directory and try to read it.

Make sure that you are not trying to open a directory for reading or writing.

2) You do not have permission to read the file

If you try to open and read a file for which you do not have the read permission, you will get this exception.

Make sure you have permission to read the file before opening and reading it.

3) Trying to overwrite a read-only file

If you try to overwrite a read-only file either using stream or writer, you will get the “Access is denied” exception.

Always check that if the file with the same name exists and it is not read-only before actually writing the file. If the file exists and it is read-only, make it writable as given in the below example.

4) Trying to create a file in the root folder of the system drive in Windows

In some versions of Windows, the system does not allow some users to write to the root of the system drive if they do not have the required privileges. Try to create a file in a subfolder, for example, C:/somedir/somefile.txt instead of the root “C:/somefile.txt”.

5) File is being used by another process

If the file is already opened exclusively by some other process, opening it for either reading or writing will cause java.io.FileNotFoundException (Access is denied) exception.

Make sure that the file is not opened by any other program or process.

This example is a part of the Java File tutorial.

Please let me know your views in the comments section below.

Источник

Оцените статью