Java Reference
In-Depth Information
System.out.println("----------------------");
printFilePath("dummy.txt");
System.out.println("----------------------");
printFilePath(".." + File.separator + "notes.txt");
}
public static void printFilePath(String pathname){
File f = new File(pathname);
System.out.println("File Name: " + f.getName());
System.out.println("File exists: " + f.exists());
System.out.println("Absolute Path: " + f.getAbsolutePath());
try {
System.out.println("Canonical Path: " + f.getCanonicalPath());
}
catch(IOException e){
e.printStackTrace();
}
}
}
Working Directory: C:\book\javabook
----------------------
File Name: dummy.txt
File exists: false
Absolute Path: C:\book\javabook\dummy.txt
Canonical Path: C:\book\javabook\dummy.txt
----------------------
File Name: notes.txt
File exists: false
Absolute Path: C:\book\javabook\..\notes.txt
Canonical Path: C:\book\notes.txt
Different operating systems use a different character to separate two parts in a pathname. For example, Windows
uses a backslash (
\
) as a name separator in a pathname, whereas UNIX uses a forward slash (
/
). The
File
class
defines a constant named
separatorChar
, which is the system-dependent name separator character. You can use the
File.separatorChar
constant to get the name separator as a character. The
File.separator
constant gives you the
name separator as a
String
. I used the name separator constant of the
File
class to build the following pathname:
printFilePath(".." + File.separator + "notes.txt");
Using the name separator in your program will make your Java code work on different platforms. The above
statement on Windows will be the same as the following statement because Windows uses a backslash (\) as a
name separator:
printFilePath("..\\notes.txt");
On UNIX, it will be the same as the following statement because UNIX uses a forward slash (/) as the file separator:
printFilePath("../notes.txt");