Java Reference
In-Depth Information
This statement creates a File object encapsulating the path to a file with the name " output.txt " in
the current directory, whatever that happens to be. It corresponds to the directory that was current
when program execution was initiated. We will see in a moment how we can obtain the absolute path
from a File object, regardless of how the File object was created.
You could also refer to a file in a subdirectory of the current directory using a relative path:
File myFile = new File("dir" + File.separator + "output.txt");
Thus we can use a relative path specification to reference files in the current directory, or in any
subdirectory of the current directory, and since a relative path does not involve the system-dependent
prefix, this will work across different operating systems.
As we have seen, an absolute path in a Windows environment can have a prefix that is an explicit drive
specification but you can also use the UNC ( U niversal N aming C onvention) representation of a path
that provides a machine-independent way of identifying paths to shared resources on a network. The
UNC representation of a path always begins with two backslashes, followed by the machine name,
followed by the share name. In general, a UNC path will be of the form:
\\servername\directory_path\filename
On a computer with the name myPC , with a shared directory shared , you could create a File object
as follows:
File myFile = new File("\\\\myPC\\shared\\jdk1.4\\src\\java\\io",
"File.java");
If you are keen to practice your typing skills, you could also write this as:
File myFile = new File(File.separator + File.separator + "myPC" +
File.separator + "shared" + File.separator +
"jdk1.4" + File.separator + "src" + File.separator +
"java" + File.separator + "io", "File.java");
If you want to create a File object that refers to the root directory under Unix, you just use " / " as the path.
Accessing System Properties
While you can specify a relative path to a file is that not system-dependent, there may be circumstances
where you want to specify a path that is independent of the current environment, but where the current
directory, or even a subdirectory of the current directory, is not a convenient place to store a data file.
In this case accessing one of the system properties can help. A system property specifies values for
parameters related to the system environment in which your program is executing. Each system
property is identified by a unique name, and has a value associated with the name that is defined as a
string. There is a set of standard system properties that will always be available and you can access the
values of any of these by passing the name of the property that you are interested in to the static
getProperty() method that is defined in the System class.
Search WWH ::




Custom Search