Java – Working with java.io.File

The java.io.File (File class for short) is a “bridge” between Java and the Operating System to read from and write to files. It can represent either a file or a directory.

How files and directories organized in file system depends on the Operating System (OS), which Java runs on. To access them, Java interfaces with the Operating System through the OS API and provides us its Java IO API – classes and interfaces.

Accessing files and directories with the File class

Let us say we have a file and directory named myfile.txt and some-directory, respectively, sitting on Windows. Their paths (or locations) are c:\Users\turreta\Desktop\myfile.txt and c:\Users\turreta\Desktop\some-directory.

To access either one of them, we create a File object initialed with a String that contains the path of the file or directory. The path can either be an absolute or relative location. An absolute path is the full path from the root directory, while a relative path is the path from the current working directory to the file or directory.

Absolute Path

An example of an absolute path:


Relative Path

An example of a relative path:


Assuming that the user’s current directory is C:\Users\turreta\Desktop. This may be the location from which Java was invoked to run some applications.

The following codes uses the File class to (try) to access a file in the Operating System. By “try”, I mean it first creates a representation of a file or directory in Java and later works on it via the File class methods. The only time we know (via return values or Exceptions) a file or directory exists or not is when we start using these methods.

The output is as follows:

However, when we use some of the File class methods:

The output is as follows: