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>
//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();
}
}
}
}
|
//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
*/
|
/*
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 >
Create File using createNewFile() method in java file IO
Find current working directory or current path in java
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 >
Find parent Directory in java
Find the available filesystem roots in java/ Available disk drives in windows
Read text entered by user in console>
Program to Read text entered by user in console using DataInputStream in java file IO
Read text entered by use in consoler using BufferedReader's readLine() method in java file IO
Program to Read text entered by use in console using java.util.Scanner
Program to Read text entered by user in console till some special character (let's say @) in java
- Read file using FileInputStream and BufferedInputStream >
Read text from file using FileInputStream in java file IO
Read text from file using BufferedInputStream (and FileInputStream) in java file IO
Write in file using FileOutputStream and BufferedOutputStream >
Write String to file using BufferedOutputStream (and FileOutputStream) in java file IO
Write String to file using BufferedWriter and FileWriter in java file IO
Program to Write in file using PrintWriter to in java
Program to Read text from file using FileInputStream and Try with resource provided in java 7
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 >
Program to Write byteArray to file using FileOutputStream in java file IO
Program to Read file in byteArray using FileInputStream in java file IO
Write in file using FileWriter and Read file using FileReader >
Program to Write to file using FileWriter in java file IO
Program to Read text from file using FileReader in java file IO
- BufferedReader and FileReader >
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 >
Should we close both FileInputStream and BufferedInputStream ? OR BufferedReader and FileReader ?
- Use Mark and Reset methods of InputStream >
Program to How to use Mark and Reset methods with BufferedInputStream
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 >
File operations - create, copy, move, rename, delete, exist?, append, hide/unHide, creation/lastModified/lastAccessed date, compare, size, Read only and writable >
Create File using createNewFile() method in java file IO
Copy a file in java 2 in ways - use org.apache.commons.io.FileUtils's copyDirectory(sourceDirectory, destDirectory)
Program to Move a file - in java file IO
Program to Rename a file - in java file IO
Program to Delete a file - in java file IO
Program to Find file exists or not - in java file IO
Program to Append to file using FileOutputStream in java file IO
Program to Hide and unHide File or Directory (by executing CMD commands in java program) till java6 - file IO
Program on How to hide and unHide file or Directory in java 7 using java.nio.file
Program to Find file is hidden or not till java 6 | And also In java 7
Program to Find creation, last modification and last accessed date of file in date, month and year in java7 using java.nio.file
Program on How to Compare two file or Directory path - in java file IO
Program to Find file size in bytes, Kilobytes, megabytes and gigabytes using length method of File in java
Program to Make a file READ ONLY in java
Program to Find file is Read only or not in java 7
Program to Make a file readable and writable in java
Program to Create Directory - Single and multiple (i.e. parent and child directories) in java file IO
Program to Identify File or Directory - in java file IO | And in java 7 using java.nio.file
2 Program to Delete a Directory - using File.delete and org.apache.commons.io.FileUtils's deleteDirectory(dir)- in java file IO
Program to Copy a Directory - using org.apache.commons.io.FileUtils's copyDirectory method- java file IO
Program to Traverse a Directory (all sub-directories and files) in 2 ways | using org.apache.commons.io.FileUtils in java file IO
- Few more >
Program to Replace all the occurrences of searchWord in the file with replaceWord in java
Program to Replace all the occurrences of searchWord in the file with replaceWord in java using byte array
Program to Sort all contents/words of file in java
Program to Sort all contents of file by line in java
Program to Create property files and store key-value pairs in it | And how to read property file in java
Program to Convert Property file to Xml File in java
Program to insert/write content at specific position in file in java
How to Read/write from file using RandomAccessFile
Skip Characters while reading text from file in java
Difference between loading file with FileInputStream and getResourceAsStream() in java
Download image from specified URL in java
How to create password protected zip files | Zip and unzip directories | zip and unzip specific files in java | Unzip JAR file
2 ways to Count number of lines in file in java
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 >
JDBC- Insert/Store/save IMAGE in database by using PreparedStatement's setBinaryStream and executeUpdate methods, using BLOB data type - in java
JDBC- Retrieve IMAGE from database by using PreparedStatement's executeQuery, ResultSet's getBlob method - using BLOB data type - in java
JDBC- Insert/Store/save FILE in database by using PreparedStatement's executeUpdate and setCharacterStream methods, using CLOB data type - in java
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?
- Please ensure file exists when you try to read from file from path exists (using FileInputStream) to avoid FileNotFoundException.
- Please ensure file exists when you try to write to file on path that doesn’t exists (using FileOutputStream) to avoid FileNotFoundException, or
- Please ensure file exists when we try to acces file from invalid path using RandomAccessFile to avoid FileNotFoundException.
- 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 >
IOException and how to solve it in java
FileNotFoundException in java
SQLException in java
What is java.lang.InterruptedException in java
when java.lang.ClassNotFoundException occurs in java
Most common and frequently occurring unchecked (runtime) in java.
What is java.lang.NullPointerException in java, when it occurs,how to handle, avoid and fix it
NumberFormatException in java
IndexOutOfBoundsException in java
When java.lang.ArrayIndexOutOfBoundsException occurs in java
When java.lang.StringIndexOutOfBoundsException occurs in java
java.lang.ArithmeticException in java - Divide number by zero
When dividing by zero does not throw ArithmeticException in java
When java.lang.IllegalStateException occurs in java
when java.lang.IllegalMonitorStateException is thrown in java
Solve java.lang.UnsupportedOperationException in java
Most common and frequently occurring Errors in java >
OutOfMemoryError in java
When java.lang.StackOverflowError occurs in java
Solve java.lang.ExceptionInInitializerError in java
How to solve java.lang.NoClassDefFoundError in java
Few More >
Labels:
Core Java
Exceptions