Java Reference
In-Depth Information
We read the path information from left to right. For example, if the path to a file is
C:\school\data\hamlet.txt , we know that the file is on the C: drive in a folder
called school and in a subfolder called data .
In the previous section, the program used the file name numbers.dat . When Java
encounters a simple name like that (also called a relative file path), it looks in the
current directory to find the file.
Current Directory (a.k.a.Working Directory)
The directory that Java uses as the default when a program uses a simple
file name.
The default directory varies with the Java environment you are using. In most
environments, the current directory is the one in which your program appears. We'll
assume that this is the case for the examples in this textbook.
You can also use a fully qualified , or complete, file name (sometimes called an
absolute file path ). However, this approach works well only when you know exactly
where your file is going to be stored on your system. For example, if you are on a
Windows machine and you have stored the file in the C:\data directory, you could
use a file name like the following:
Scanner input = new Scanner(new File("C:/data/numbers.dat"));
Notice that the path is written with forward-slash characters rather than backslash
characters. On Windows you would normally use a backslash, but Java allows you to
use a forward slash instead. If you wanted to use a backslash, you would have to use a
\\ escape sequence. Most programmers choose the simpler approach of using forward-
slash characters because Java does the appropriate translation on Windows machines.
You can also specify a file using a relative path . To write a relative path you omit
the drive specification at the beginning of the string. You can still specify subdirec-
tory relationships that will be relative to the current directory. For example, the rela-
tive path "data/numbers.dat" indicates a file called numbers.dat in a subdirec-
tory of the working directory called data .
Sometimes, rather than writing a file's path name in the code yourself, you'll ask
the user for a file name. For example, here is a variation of ShowSum2 that prompts
the user for the file name:
1 // Variation of ShowSum2 that prompts for a file name.
2
3 import java.io.*;
4 import java.util.*;
5
6 public class ShowSum4 {
7 public static void main(String[] args)
8 throws FileNotFoundException {
 
Search WWH ::




Custom Search