Java Reference
In-Depth Information
For instance, the directory that is the default base for relative paths is defined by the property that has
the name " user.dir ", so we can access the path to this directory with the statement:
String currentDir = System.getProperty("user.dir");
We could then use this to specify explicitly where the file with the name " output.txt " is located:
File dataFile = new File(currentDir, "output.txt");
Of course, this is equivalent to just specifying the file name as the relative path, so we have not achieved
anything new. However, there is another system property with the name " user.home " that has a value
that defines a path to the user's home directory. We could therefore specify that the " output.txt " file
is to be in this directory like this:
File dataFile = new File(System.getProperty("user.home"), "output.txt");
The location of the user's home directory is system-dependent, but wherever it is you can access it in
this way without building system dependencies into your code.
Naturally, you could specify the second argument to the constructor here to include directories that are
to be subdirectories of the home directory. For instance:
File dataFile = new File(System.getProperty("user.home"),
"dir" + File.separator + "output.txt");
On my system this defines the path:
C:\Documents and Settings\Ivor Horton\dir\output.txt
If you want to plug this code fragment into a main() method and see what path the resultant File
object encapsulates, the following statement will output the absolute path for you.
System.out.println(dataFile.getAbsolutePath());
This uses the getAbsolutePath() method for the File object to obtain the absolute path as a
reference to a String object. We will come back to this method in a moment.
If you would like to see what the full set of standard system properties are, you will find the complete
list in the SDK documentation for the getProperties() method in the System class.
Testing and Checking File Objects
The File class provides more than 30 methods that you can apply to File objects, so we will look at
the ones that will be most useful, grouped by the sorts of things that they do.
First of all, you can get information about a File object itself by using the following methods:
Search WWH ::




Custom Search