FileNotFoundException in java, how to avoid it


What is hierarchy of java.lang. FileNotFoundException?

-java.lang.Object
-java.lang.Throwable
 -java.lang.Exception
  -java.lang.IOException
   -java.lang.FileNotFoundException


FileNotFoundException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java ?

java.lang.FileNotFoundException is a Checked (compile time) Exception in java.


What is FileNotFoundException in java?

FileNotFoundException could be generated
  • When try to read from file from path that doesn’t exists (using FileInputStream) could throw compile time FileNotFoundException.
  • When try to write to file on path that doesn’t exists (using FileOutputStream) could throw compile time FileNotFoundException, or
  • When we try to acces file from invalid path using RandomAccessFile could throw compile time FileNotFoundException.

  • FileNotFoundException could also be generated when file exists but its is inaccessible may be because of some security reasons.


Example/Programs/Scenarios where FileNotFoundException may be thrown in java>

  1. When try to read from file from path that doesn’t exists (using FileInputStream).
//Read text from file using FileInputStream in java file IO
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class ReadFileUsingFileInputStream {
   public static void main(String... args) {
          FileInputStream fis = null;
          try {
                 // if file doesn't exist FileNotFoundException will be thrown at
                 // runtime
                 fis = new FileInputStream("c:/myFile.txt");
                 System.out.println("Reading from text file using FileInputStream > ");
                 int ch;
                 while ((ch = fis.read()) != -1) { //read till end of file
                       System.out.print((char) ch);
                 }
          } catch (FileNotFoundException fnfe) {
                 fnfe.printStackTrace();
          } catch (IOException e) {
                 // TODO Auto-generated catch block
                 e.printStackTrace();
          } finally {
                 try {
                       if (fis != null)
                              fis.close(); //close FileInputStream
                 } catch (IOException e) {
                       e.printStackTrace();
                 }
          }
   }
}

  1. When try to write to file on path that doesn’t exists (using FileOutputStream),
//Write String to file using FileOutputStream in java file IO
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/** JavaMadeSoEasy.com */
public class WriteStringToFileUsingFileOutputStream {
   public static void main(String... args) {
          FileOutputStream fos = null;
          try {
                 // if file doesn't exist new file will be created
                 // if file already exists contends will be overridden.
                 fos = new FileOutputStream("c:/myFile.txt");
                 String str="You are learning File IO from javaMadeSoEasy.com";
                 fos.write(str.getBytes()); //convert String into byte array to write in file
                
                 fos.flush(); //bytes in buffer are written in file
                
                 System.out.println("String str has been written successfully in file "
                              + "using FileOutputStream");
                
          } catch (FileNotFoundException fnfe) {
                 fnfe.printStackTrace();
          } catch (IOException ioe) {
                 // TODO Auto-generated catch block
                 ioe.printStackTrace();
          } finally {
                 try {
                       if (fos != null){
                              fos.close(); //close FileOutputStream
                       }
                 } catch (IOException e) {
                       e.printStackTrace();
                 }
          }
   }
}
/* OUTPUT
String str has been written successfully in file using FileOutputStream
*/

  1. Or, when we try to acces file from invalid path using RandomAccessFile.

/*
RandomAccessFile allows us to read/write at random positions
By using seek method we can move to random position,
   if seek is set beyond the length the file and we try to read from there than java.io.EOFException is thrown.
*/
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileTest {
   public static void main(String[] args) {
          try {
                 String fileName = "c:/myFile.txt";
                 String data = "abcdef";
                 RandomAccessFile randomAccessFile;
                
                 // ---- Writing in file using RandomAccessFile ----
                 // 'rw' means opening file in Read-Write mode
                 randomAccessFile = new RandomAccessFile(fileName, "rw");
                 randomAccessFile.seek(5);
                 randomAccessFile.writeUTF(data);
                 System.out.println("Data written in "+" = "+data);
                 randomAccessFile.close();
                 // ---- Reading from file using RandomAccessFile ----
                 // 'r' means opening file in Read mode
                 randomAccessFile = new RandomAccessFile(fileName, "r");
                 randomAccessFile.seek(5);
                 data = randomAccessFile.readUTF();
                 System.out.println("Data read from file = "+data);
                 randomAccessFile.close();
          } catch (FileNotFoundException fnfe) {
                 fnfe.printStackTrace();
          } catch (IOException ioe) {
                 // TODO Auto-generated catch block
                 ioe.printStackTrace();
          }
   }
}
/*
Data written in file = abcdef
Data read from file = abcdef
*/

Here I am posting more program links (76 programs) which can throw FileNotFoundException in java >
  1. Create File using createNewFile() method in java file IO

  2. Find current working directory or current path in java

  3. Create File in current path using new File(currentPath, fileName), File.separator or System.getProperty("file.separator") in java file IO

Find parent Directory and available disk drives in system >
  1. Find parent Directory in java

  2. Find the available filesystem roots in java/ Available disk drives in windows

Read text entered by user in console>
  1. Program to Read text entered by user in console using DataInputStream in java file IO

  2. Read text entered by use in consoler using BufferedReader's readLine() method in java file IO

  3. Program to Read text entered by use in console using java.util.Scanner

  4. Program to Read text entered by user in console till some special character (let's say @) in java


  1. Read file using FileInputStream and BufferedInputStream >
  2. Read text from file using FileInputStream in java file IO

  3. Read text from file using BufferedInputStream (and FileInputStream) in java file IO

Write in file using FileOutputStream and BufferedOutputStream >
  1. Write String to file using BufferedOutputStream (and FileOutputStream) in java file IO

  2. Write String to file using BufferedWriter and FileWriter in java file IO

  3. Program to Write in file using PrintWriter to in java

  4. Program to Read text from file using FileInputStream and Try with resource provided in java 7

  5. Program to Read text from file in String using BufferedInputStream and Try with resource provided in java 7

Write byte Array in file and read it >
  1. Program to Write byteArray to file using FileOutputStream in java file IO

  2. Program to Read file in byteArray using FileInputStream in java file IO

Write in file using FileWriter and Read file using FileReader >
  1. Program to Write to file using FileWriter in java file IO

  2. Program to Read text from file using FileReader in java file IO

  3. BufferedReader and FileReader >
  4. Program to Read text from file using BufferedReader's read() and readLine() methods in java file IO

Should we close both FileInputStream and BufferedInputStream | BufferedReader and FileReader >
  1. Should we close both FileInputStream and BufferedInputStream ? OR BufferedReader and FileReader ?

  2. Use Mark and Reset methods of InputStream >
  3. Program to How to use Mark and Reset methods with BufferedInputStream

  4. Program to How to use Mark and Reset methods with BufferedReader

Encrypt and decrypt text using password - Write encrypted text to file and Read encrypted text from file in java >
  1. Program to Encrypt and decrypt text using password - Write encrypted text to file | Read encrypted text from file in java

  1. Create File using createNewFile() method in java file IO

  2. Copy a file in java 2 in ways - use org.apache.commons.io.FileUtils's copyDirectory(sourceDirectory, destDirectory)

  3. Program to Move a file - in java file IO

  4. Program to Rename a file - in java file IO

  5. Program to Delete a file - in java file IO

  6. Program to Find file exists or not - in java file IO

  7. Program to Append to file using FileOutputStream in java file IO

  8. Program to Hide and unHide File or Directory (by executing CMD commands in java program) till java6 - file IO

  9. Program on How to hide and unHide file or Directory in java 7 using java.nio.file

  10. Program to Find file is hidden or not till java 6 | And also In java 7

  11. Program to Find creation, last modification and last accessed date of file in date, month and year in java7 using java.nio.file

  12. Program on How to Compare two file or Directory path - in java file IO

  13. Program to Find file size in bytes, Kilobytes, megabytes and gigabytes using length method of File in java

  14. Program to Make a file READ ONLY in java

  15. Program to Find file is Read only or not in java 7

  16. Program to Make a file readable and writable in java

Directory operations - create, identify, delete, copy, traverse >
  1. Program to Create Directory - Single and multiple (i.e. parent and child directories) in java file IO

  2. Program to Identify File or Directory - in java file IO | And in java 7 using java.nio.file

  3. 2 Program to Delete a Directory - using File.delete and org.apache.commons.io.FileUtils's deleteDirectory(dir)- in java file IO

  4. Program to Copy a Directory - using org.apache.commons.io.FileUtils's copyDirectory method- java file IO

  5. Program to Traverse a Directory (all sub-directories and files) in 2 ways | using org.apache.commons.io.FileUtils in java file IO

  6. Few more >
  7. Program to Replace all the occurrences of searchWord in the file with replaceWord in java

  8. Program to Replace all the occurrences of searchWord in the file with replaceWord in java using byte array

  9. Program to Sort all contents/words of file in java

  10. Program to Sort all contents of file by line in java

  11. Program to Create property files and store key-value pairs in it | And how to read property file in java

  12. Program to Convert Property file to Xml File in java

  13. Program to insert/write content at specific position in file in java

  14. How to Read/write from file using RandomAccessFile

  15. Skip Characters while reading text from file in java

  16. Difference between loading file with FileInputStream and getResourceAsStream() in java

  17. Download image from specified URL in java

  18. How to create password protected zip files | Zip and unzip directories | zip and unzip specific files in java | Unzip JAR file

  19. 2 ways to Count number of lines in file in java

  20. SequenceInputStream to read data from multiple files (two or more) and writing it in one file in java

Customizing  Serialization process by implementing Serializable and Externalizable >
  1. Avoid ObjectInputStream.readObject() from throwing EOFException at End Of File in java  

IMAGE - Storing in and retrieving out from database
  1. JDBC- Insert/Store/save IMAGE in database by using PreparedStatement's setBinaryStream and executeUpdate methods, using BLOB data type - in java

  2. JDBC- Retrieve IMAGE from database by using PreparedStatement's executeQuery, ResultSet's getBlob method - using BLOB data type - in java

FILE - Storing in and retrieving out from database
  1. JDBC- Insert/Store/save FILE in database by using PreparedStatement's executeUpdate and setCharacterStream methods, using CLOB data type - in java

  2. JDBC- Retrieve FILE from database by using PreparedStatement's executeQuery and ResultSet's getClob method, using CLOB data type - in java


How to avoid FileNotFoundException in java?
  1. Please ensure file exists when you try to read from file from path  exists (using FileInputStream) to avoid FileNotFoundException.
  2. Please ensure file exists when you try to write to file on path that doesn’t exists (using FileOutputStream) to avoid FileNotFoundException, or
  3. Please ensure file exists when we try to acces file from invalid path using RandomAccessFile to avoid FileNotFoundException.
  4. Please ensure that file you are trying to access is completely accessible and have no security constraints refraining you from accessing files to avoid FileNotFoundException..

Summary >
So in this Exception handling java tutorial we learned. What is hierarchy of java.lang. FileNotFoundException? java.lang.FileNotFoundException is a Checked (compile time) Exception in java. What is FileNotFoundException in java? Example/Programs/Scenarios where FileNotFoundException may be thrown in java. How to avoid FileNotFoundException in java?

Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.

RELATED LINKS>

Most common and frequently occurring checked (compile time) and Errors in java >

Most common and frequently occurring unchecked (runtime) in java.

Most common and frequently occurring Errors in java >

Few More >




No comments:

Post a Comment