Java, Software Development

Understanding How Java Works With Files

The Java java.io.File (File class for short) connects 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 are organized in the file system depends on the Operating System, 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 in Java with the File class

Let us say we have a file and directory 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 a full path from the root directory, while a relative path is a location from the current working directory to the file or directory.

An example of an absolute path would be the following example.

Meanwhile, the following path is relative (to the current directory).

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

The following codes use 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 codes generate the following output, and they did not create any file or directory.

However, when using some of the File class methods, Java actually detects the file or directory.

The program creates the following result.

This post is (now) part of a reboot Java tutorial.

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like