FileNotFoundException in Java

Previous
Next

In this post, we will see about FileNotFoundException in java.

FileNotFoundException is thrown by constructors of FileInputStream, FileOutputStream, RandomAccessFile when file is not found on specified path. Exception can also be raised when file is inaccessible for some reason.For example: When you do not have proper permissions to read the files.

FileNotFoundException is checked exception so you need to handle by java code. You should take proper action to print appropriate exception to the user if FileNotFoundException is thrown.

Let’s understand with the help of example.

When you run above program, you will get below output:

java.io.FileNotFoundException: C:/Java2blog.txt (No such file or directory)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:196)
at java.base/java.io.FileInputStream.(FileInputStream.java:139)
at org.arpit.java2blog.FileReadExample.main(FileReadExample.java:17)
Exception in thread “main” java.lang.NullPointerException
at org.arpit.java2blog.FileReadExample.main(FileReadExample.java:27)

As you can see if file is not present in the path, we are getting FileNotFoundException.


How to resolve FileNotFoundException

  • Check if passed file is present in specified file
  • Check if passed file is actually directory
  • The passed file can not be open due to permission issues. You might be trying to write to file where as you only have read permission.
  • Check if passed file name does not contain any invisible characters such as \r\n symbols.

That’s all about FileNotFoundException in java.

 

Previous
Next

Add Comment