Creating FileInputStream: Constructor Options and File Paths
What you'll learn: How to instantiate FileInputStream objects using different constructors and understand when file-related exceptions occur.
Constructor Options
FileInputStream provides two primary constructors for opening files:
1. Using a String Path
FileInputStream fis = new FileInputStream("data.txt");
This constructor accepts a String representing the file path. The path can be:
- Relative:
"data.txt"or"input/data.txt"(relative to your program's working directory) - Absolute:
"/home/user/data.txt"or"C:\\data\\file.txt"
2. Using a File Object
File file = new File("data.txt");
FileInputStream fis = new FileInputStream(file);
This constructor takes a File object, which you create separately. This approach is useful when you need to check file properties (like existence or readability) before opening the stream.
Understanding FileNotFoundException
Both constructors throw FileNotFoundException (a checked exception) if:
- The file doesn't exist
- The path is a directory, not a file
- The file cannot be opened due to permission issues
You must handle this exception:
try {
FileInputStream fis = new FileInputStream("data.txt");
// read operations...
fis.close();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
Think of it like this: You're asking Java to open a specific book from a library. If that book doesn't exist or is locked away, Java throws FileNotFoundException to tell you it can't fulfill your request.
When to Use Which Constructor
- Use the
Stringconstructor for simple, straightforward file opening - Use the
Fileconstructor when you need to validate or manipulate the file path first
Key Takeaway: FileInputStream can be created with either a String path or a File object, but both require handling FileNotFoundException since the file may not exist or be accessible at runtime.