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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package org.arpit.java2blog; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * FileNotFoundException example * @author Arpit * */ public class FileReadExample { public static void main(String[] args) { File file = new File("C:/Java2blog.txt"); FileInputStream fis = null; try{ fis = new FileInputStream(file); while (fis.read()!=-1){ System.out.println(fis.read()); } }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally{ try{ fis.close(); }catch (IOException e){ e.printStackTrace(); } } } } |
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.