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.
1 | C:\Users\turreta\Desktop\myfile.txt |
Meanwhile, the following path is relative (to the current directory).
1 | myfile.txt |
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.
1 2 3 4 5 6 7 8 9 10 | package com.turreta.ocp.io; import java.io.File; public class FileDemo { public static void main(String[] args) { File file = new File("C:\\Users\\turreta\\Desktop"); System.out.println("Nothing else happened."); } } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 | package com.turreta.ocp.io; import java.io.File; public class FileDemo { public static void main(String[] args) { File file = new File("C:\\Users\\turreta\\Desktop"); System.out.println("Existing?" + file.exists()); System.out.println("Is a directory?" + file.isDirectory()); System.out.println("Is a file?" + file.isFile()); System.out.println("Nothing else happened."); } } |
The program creates the following result.
This post is (now) part of a reboot Java tutorial.