Java Input/Output  «Prev   Next»

Lesson 5Files
ObjectiveFile Class to access Files

File Class to Access Files

The File class provides a way to deal with the file system as platform-independently as possible. Instances of File represent nodes in the file system and either files or directories. When you create an instance of class File, you specify a directory or file that you would like this instance to represent. Specifying this directory or file must be accomplished by specifying the absolute or relative path, which can, unfortunately, be platform-specific. For example, whether you use forward slashes, backward slashes, or colons to indicate directory hierarchies depends on whether you are using the Unix, Windows, or Mac operating system.
However, the File class does provide some ways around these types of problems. For example, there is a class variable called pathSeparatorChar that contains the appropriate separator for the OS on which your program is running. There are also methods for testing whether or not a file exists, for creating a new directory, for testing whether you can read from or write to a particular file, and for deleting a file. Check out the File class in the APIs for more information on this class.

Java "File Class" from Java1.1 on Windows machine

The `File` class in Java (introduced in Java 1.0, not Java 1.1) provides an abstraction for file and directory pathnames and allows Java programs to interact with the file system in a platform-independent way. When it comes to accessing files on a Windows machine, the `File` class handles path representations and access using the following mechanisms:
Path Representation
  1. Path Separator (\):
    • On Windows, paths use the backslash (\) as a separator (e.g., C:\Users\Documents). However, the File class abstracts this by accepting both forward slashes (/) and backslashes (\).
    • Internally, it converts paths to the format required by the underlying operating system. For instance:
      File file = new File("C:/Users/Documents/example.txt"); // Works on Windows
              
  2. Drive Letters:
    • Windows uses drive letters (e.g., C:\, D:\) to represent partitions or logical drives. The File class allows specifying absolute paths, including drive letters:
      File file = new File("C:\\Users\\Documents\\example.txt");
              
  3. Relative Paths:
    • You can specify paths relative to the current working directory (e.g., new File("example.txt")), and the File class resolves them based on the user.dir system property.


Accessing Files:
The `File` class interacts with the Windows file system through:
  1. Native Code:
    • Java's File operations delegate low-level file handling tasks (like reading, writing, or checking metadata) to the Java Native Interface (JNI), which communicates with the operating system's native file-handling APIs.
  2. Key Methods:
    • Existence Check:
      boolean exists = file.exists();
              
      This checks if a file or directory exists.
    • File Creation:
      boolean created = file.createNewFile();
              
      Creates a new file if it does not already exist.
    • Directory Listing:
      String[] files = directory.list();
              
      Retrieves a list of files and directories in a given directory.
    • File Deletion:
      boolean deleted = file.delete();
              
      Deletes the specified file or directory.
    • Path Information:
      String absolutePath = file.getAbsolutePath();
              
      Returns the full path of the file.
  3. File Permissions:
    • The File class provides methods to check and set file permissions:
      boolean isReadable = file.canRead();
      boolean isWritable = file.canWrite();
      boolean success = file.setReadOnly();
              

Case Sensitivity
  • On Windows, the file system is case-insensitive but case-preserving. The `File` class respects this behavior:
    • `new File("example.txt")` and `new File("Example.TXT")` would both refer to the same file on Windows.

Legacy Windows Behavior In early Java versions (like 1.1), the `File` class depended heavily on the platform's file system conventions:
  • It used java.io.FileSystem internally to manage platform-specific differences.
  • The Windows implementation mapped file operations to the Win32 API for tasks like retrieving file metadata or accessing directories.

Limitations of the File Class
  1. The File class does not provide direct file content manipulation (e.g., reading or writing bytes). For that, classes like FileInputStream, FileOutputStream, BufferedReader, etc., are used.
  2. The File class has limited support for symbolic links or advanced file attributes. The java.nio.file package (introduced in Java 7) addresses these shortcomings.

By abstracting platform-specific details, the `File` class ensures a consistent API for file access across Windows and other operating systems.

Reading File - Exercise

This exercise leads you through reading from a file.
Reading File - Exercise

Java IO - Quiz

Once you have reached the end of the I/O section, refresh what you have learned with a few simple questions.
Java IO - Quiz

SEMrush Software