Creating FileReader Instances with File Paths
You'll learn: How to construct FileReader objects using different path representations to read text files in Java.
The Three Ways to Open a File for Reading
When you want to read a text file with FileReader, Java gives you three constructor options, each accepting a different way of specifying which file to open. Think of these as three different ways to give directions to the same house: a street address (String), a location object (File), or a low-level identifier (FileDescriptor).
Constructor #1: String File Path
The simplest approach uses a String containing the file path:
FileReader reader = new FileReader("data.txt");
This works with absolute paths ("/home/user/data.txt") or relative paths ("data.txt"). The path follows your operating system's conventions (forward slashes on Unix/Linux, backslashes on Windows, though forward slashes work on both).
Constructor #2: File Object
You can also pass a File object, which is useful when you've already created one or need to check file properties first:
File file = new File("data.txt");
FileReader reader = new FileReader(file);
This approach is common when you want to verify the file exists or is readable before attempting to open it.
Constructor #3: FileDescriptor
The least common option uses a FileDescriptor, a low-level handle typically obtained from other I/O operations:
FileDescriptor fd = // obtained from another source
FileReader reader = new FileReader(fd);
This is advanced usage, typically for interoperating with native code or already-open files.
When to Use Which?
Use String paths for simple, straightforward cases. Use File objects when you need file metadata or path manipulation. Use FileDescriptor only in specialized scenarios involving system-level file handles.
Key Takeaway: FileReader provides three constructors—String paths for simplicity, File objects for flexibility with file operations, and FileDescriptor for low-level file handle reuse.