Java Reference
In-Depth Information
System.out.println(myFile + (myFile.isHidden() ? " is" : " is not")
+ " hidden");
System.out.println("You can" + (myFile.canRead() ? " " : "not ")
+ "read " + myFile);
System.out.println("You can" + (myFile.canWrite() ? " " : "not ")
+ "write " + myFile);
return;
}
}
On my machine, the above example produces the output:
C:\j2sdk1.4.0\src\java\io is a directory.
C:\j2sdk1.4.0\src\java\io\File.java does exist
C:\j2sdk1.4.0\src\java\io\File.java is a file.
C:\j2sdk1.4.0\src\java\io\File.java is not hidden
You can read C:\j2sdk1.4.0\src\java\io\File.java
You can write C:\j2sdk1.4.0\src\java\io\File.java
How It Works
This program first creates an object corresponding to the directory containing the
java.io
package.
You will need to check the path to this directory on your own system and insert that as the argument to
the constructor of the
File
object. The output statement then uses the conditional operator
?:
in
conjunction with the
isDirectory()
method to display a message. If
isDirectory()
returns true,
then "
is
" is selected. Otherwise, "
is
not
" is selected. The program then creates another
File
object
corresponding to the file
File.java
and displays further information about the file using the same sort
of mechanism. Finally, the program uses the
canRead()
and
canWrite()
methods to determine
whether read and write access to the file is permitted.
If you are using MS Windows, you might like to try out the separator
\\
with this example and see if it
makes a difference.
The following methods provide further information about the file or directory, if it exists:
Method
Description
list()
If the current
File
object represents a directory, a
String
array
is returned containing the names of the members of the directory.
If the directory is empty, the array will be empty. If the current file
object is a file,
null
is returned. The method will throw an
exception of type
SecurityException
if access to the directory
is not authorized.
listFiles()
If the object for which this method is called is a directory, it
returns an array of
File
objects corresponding to the files and
directories in that directory. If the directory is empty, then the
array that is returned will be empty. The method will return
null
if the object is not a directory, or if an I/O error occurs. The
method will throw an exception of type
SecurityException
if
access to the directory is not authorized.