23.07.2013 Views

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

Java IO.pdf - Nguyen Dang Binh

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Example 12.2. Paths<br />

import java.io.*;<br />

public class Paths {<br />

}<br />

public static void main(String[] args) {<br />

}<br />

File absolute = new File("/public/html/javafaq/index.html");<br />

File relative = new File("html/javafaq/index.html");<br />

System.out.println("absolute: ");<br />

System.out.println(absolute.getName());<br />

System.out.println(absolute.getPath());<br />

System.out.println("relative: ");<br />

System.out.println(relative.getName());<br />

System.out.println(relative.getPath());<br />

When the program is run on Unix, here's the output:<br />

% java Paths<br />

absolute:<br />

index.html<br />

/public/html/javafaq/index.html<br />

relative:<br />

index.html<br />

html/javafaq/index.html<br />

<strong>Java</strong> I/O<br />

On Windows with <strong>Java</strong> 2, the output's a little different, because the File constructor<br />

normalizes the file separator character to the backslash:<br />

D:\JAVA\ioexamples\12>java Paths<br />

absolute:<br />

index.html<br />

\public\html\javafaq\index.html<br />

relative:<br />

index.html<br />

html\javafaq\index.html<br />

12.3.3.3 Absolute paths<br />

The getAbsolutePath() method returns the complete path to the file starting from a<br />

filesystem root:<br />

public String getAbsolutePath()<br />

Examples of absolute paths include /public/html/javafaq/index.html and<br />

D:\JAVA\ioexamples\12 but not html/javafaq/index.html or ioexamples\12. If the File object's<br />

path field is already an absolute path, then its value is returned. Otherwise, a separator<br />

character and the value of the path field are appended to the value of the system property<br />

user.dir, which refers to the current working directory. This method throws a security<br />

exception in most applet environments, because applets are usually not allowed to read the<br />

user.dir property.<br />

285

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!