Java Reference
In-Depth Information
File
, which also is part of the
java.io
package, represents a file or folder reference. The
following
File
constructors can be used:
File(
String
)
—Creates a
File
object with the specified folder; no filename is
indicated, so this refers only to a file folder.
n
15
File(
String
,
String
)
—Creates a
File
object with the specified folder path and
the specified name.
n
File(
File
,
String
)
—Creates a
File
object with its path represented by the spec-
ified
File
and its name indicated by the specified
String
.
n
You can call several useful methods on a
File
object.
The
exists()
method returns a Boolean value indicating whether the file exists under
the name and folder path established when the
File
object was created. If the file exists,
you can use the
length()
method to return a
long
integer indicating the size of the file
in bytes.
The
renameTo(
File
)
method renames the file to the name specified by the
File
argu-
ment. A Boolean value is returned, indicating whether the operation was successful.
The
delete()
or
deleteOnExit()
method should be called to delete a file or a folder.
The
delete()
method attempts an immediate deletion (returning a Boolean value indi-
cating whether it worked). The
deleteOnExit()
method waits to attempt deletion until
the rest of the program has finished running. This method does not return a value—you
couldn't do anything with the information—and the program must finish at some point
for it to work.
The
getName()
and
getPath()
methods return strings containing the name and path of
the file.
Several methods are useful when the
File
object represents a folder rather than a file.
The
mkdir()
method can be used to create the folder specified by the
File
object it is
called on. It returns a Boolean value indicating success or failure. There is no compara-
ble method to remove folders—
delete()
can be used on folders as well as files.
The
isDirectory()
method returns the Boolean value
true
when the
File
object is a
folder and
false
otherwise.
The
listFiles()
method returns an array of
File
objects representing the contents of
the folder—all its files and subfolders.