The Java 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
The 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
.
Another example:
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
File
contains various interesting features for specific use cases, such as:
getParentFile
: returns aFile
pointing to the directory that contains the current file or directory.getAbsoluteFile
: returns another instance ofFile
with an absolute path.toURI
: returns a URI (Universal Resource Identifier) that begins withfile:
. It’s useful to network operations.isFile
eidDirectory
: tells ifFile
points to a file or directory, respectively.exists
: tells if the file or directory really exists in filesystem.canRead
ecanWrite
: 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.list
elistFiles
: lists files and directories, ifFile
is a directory.mkdir
emkdirs
: creates a new directory, ifFile
is a directory. The latter also creates parent directories if needed.getFreeSpace
: returns the available space in the device to whereFile
is pointing to.createTempFile
: static method that returns an unique temporary file to be used by the application. The methoddeleteOnExit
will delete the file at the termination of the program.
The class 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!