File class encapsulates the filesystem in a simplified manner. Its constructor accepts absolute and relative (to the working directory of the program) paths. For instance:
new File(".") //--> program's current directory
But using relative paths can cause trouble in some situations, since the working directory could be modified. Besides that, if there are input fields for file paths you should avoid relative paths unless in special cases like if the selected file is part of your program.
Checking if a path is relative
File.isAbsolute() method gives us a hand in this task, telling if the path is absolute. Example:
File f1 = new File(".."); System.out.println(f1.isAbsolute()); //prints false File f2 = new File("c:\\temp"); System.out.println(f2.isAbsolute()); //prints true
How to get the absolute path
Another useful method is
getAbsolutePath(). It returns the absolute path to an instance of
File f1 = new File("\\directory\\file.xml"); System.out.println(f1.getAbsolutePath()); //prints C:\directory\file.xml File f2 = new File("c:\\directory\\file.xml"); System.out.println(f2.getAbsolutePath()); //prints c:\directory\file.xml
Other nice features of
File contains various interesting features for specific use cases, such as:
getParentFile: returns a
Filepointing to the directory that contains the current file or directory.
getAbsoluteFile: returns another instance of
Filewith an absolute path.
toURI: returns a URI (Universal Resource Identifier) that begins with
file:. It’s useful to network operations.
idDirectory: tells if
Filepoints to a file or directory, respectively.
exists: tells if the file or directory really exists in filesystem.
canWrite: tells if you can read or write to the file, respectively.
createNewFile: creates a new blank file.
delete: removes the file or directory (if empty).
length: retuns the file size in bytes.
listFiles: lists files and directories, if
Fileis a directory.
mkdirs: creates a new directory, if
Fileis a directory. The latter also creates parent directories if needed.
getFreeSpace: returns the available space in the device to where
Fileis pointing to.
createTempFile: static method that returns an unique temporary file to be used by the application. The method
deleteOnExitwill delete the file at the termination of the program.
File also contains some important static attributes useful to read and write files in different platforms:
File.separator: path-name separator character. On Unix and Linux it is
/, while on Windows it is
File.pathSeparator: path-separator character, in order to create a path list with various directories, like PATH system variable. On Unix and Linux it is
:, while on Windows it is
This article was based on my answer on StackOverflow in Portuguese!