📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this blog post, we will learn what is FileNotFoundException, how it occurs, practical examples, potential solutions, and best practices.
Understanding FileNotFoundException
The FileNotFoundException is a checked exception that indicates that a file with the specified pathname does not exist. Alternatively, in some scenarios, it can mean the application does not have adequate permissions to access the file.
As FileNotFoundException is a checked exception in Java so you're required to handle it, either by catching it or declaring it in the method signature using the throws keyword.
FileNotFoundException Class Diagram
Why Does It Occur?
Practical Example
import java.io.FileReader;
import java.io.IOException;
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("non_existent_file.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
java.io.FileNotFoundException: non_existent_file.txt (The system cannot find the file specified)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:219)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:158)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:112)
at java.base/java.io.FileReader.<init>(FileReader.java:60)
at com.javaguides.net.FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:9)
Comments
Post a Comment
Leave Comment