Java Reference
In-Depth Information
The File class includes several overloaded constructors. For example, the
following instance of File refers to a file named myfile.txt in the current
directory where the JVM is running:
File file = new File ( " myfile.txt " );
Again, the file myfile.txt may or may not exist in the file system. An attempt
to use a File object that refers to a file that does not exist will cause a FileNot-
FoundException to be thrown.
The next example creates a File object from a file name that includes the
full directory path:
File file = new File ("/tmp/myfile.txt");
Another overloaded constructor allows the separate specification of path and file
name:
File file = new File ("/tmp", "myfile.txt");
File objects can also represent directories. For example,
File tmp - directory = new File ( " /tmp " );
There are a number of useful methods in File such as the following:
Boolean exist () - indicates if the file referred to actually exists
Boolean canWrite () - can the file be written to
Boolean canRead () - can the file be read
Boolean isFile () - does the File object represent a file?
Boolean isDirectory () -oradirectory?
Given an instance of File , the class provides methods to obtain the file name and
path components, to make a directory, to get a listing of the files in a directory,
and so forth:
String getName () - get the name of the file (no path included)
String getPath () - get the abstract file path
String getCanonicalPath () - get the name of the file with path
String getAbsolutePath () - get the absolute file path
Java must run on different types of platforms, and file and directory systems differ
among platforms. For example, path names use different separator characters on
different hosts. Windows uses the backslash (“ \ ”) and Unix uses the forward slash
(“ / ”). To obtain platform independence, instead of explicit separator characters,
you can use these static constants defined in the File class:
File.separator - String with file separator
File.separatorChar - char with file separator
File.pathSeparator - String with path separator
File.pathSeparatorChar - char with path separator
Search WWH ::




Custom Search