Java Reference
In-Depth Information
Querying Files and Directories
The following basic set of methods are provided for examining the file or directory that is identified by
a
File
object:
Method
Description
exists()
Returns
true
if the file or directory referred to by the
File
object exists and
false
otherwise.
isDirectory()
Returns
true
if the
File
object refers to an existing directory
and
false
otherwise.
isFile()
Returns
true
if the
File
object refers to an existing file and
false
otherwise.
isHidden()
Returns
true
if the
File
object refers to a file that is hidden
and
false
otherwise. How a file is hidden is system-dependent.
Under Unix a hidden file has a name that begins with a dot.
Under Windows a file is hidden if it is marked as such within the
file system.
canRead()
Returns
true
if you are permitted to read the file referred to by
the
File
object, and
false
otherwise. This method can throw a
SecurityException
if read access to the file is not permitted.
canWrite()
Returns
true
if you are permitted to write to the file referred to
by the
File
object and
false
otherwise. This method may also
throw a
SecurityException
if you are not allowed to write to
the file.
getAbsolutePath()
Returns the absolute path for the directory or file referenced by
the current
File
object. If the object contains an absolute path,
then the string returned by
getPath()
is returned. Otherwise,
under MS Windows the path is resolved against the current
directory for the drive identified by the pathname, or against the
current user directory if no drive letter appears in the pathname,
and against the current user directory under UNIX.
getAbsoluteFile()
Returns a
File
object containing the absolute path for the
directory or file referenced by the current
File
object.
When you are working with a
File
object, you may not know whether it contains an absolute or a
relative path. However, you may well want to get hold of its parent directory - to create another file for
instance. For a
File
object created from a relative path, the
getParent()
method will return
null
.
In this case you can use the
getAbsolutePath()
method to obtain the absolute path, or the
getAbsoluteFile()
method to ensure that you have a
File
object for which the
getParent()
method will return a string representing the complete path for the parent directory. For instance:
File dataFile = new File("output.txt");