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:
C:\Users\turreta\Desktop\myfile.txt
Relative Path
An example of a relative path:
myfile.txt
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.
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 output is as follows:
However, when we use some of the File
class methods:
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 output is as follows:
Recent Comments