File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes File Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "File Class" Watch "File Class" New topic

File Class

Steven Wong
Ranch Hand

Joined: Mar 07, 2002
Posts: 295
I'm a bit confused over the methods of the File class: getAbsolutePath, getCanonicalPath, getPath.
What's the difference to the 3 above?
Hope someone could help me out.

best regards,<br />Steven<br />SCJP, SCEA
Jamal Hasanov
Ranch Hand

Joined: Jan 08, 2002
Posts: 411
A quote from Khalid Mugal's book
(Chapter 18-Files&Streams,page 552)
For example, if the File object represented the absolute pathname "c:\book\ chapter1" on Windows, then this pathname would be returned by these methods.On the other hand, if the File object represented the relative pathname "..\book\chapter1" and the current directory had the absolute pathname "c:\documents", the pathname returned by the getPath(), getAbsolutePath() and getCanonicalPath() methods would be "..\book\chapter1", "c:\documents\..\book\chapter1" and "c:\book\chapter1", respectively.
BTW, you can download this chapter in PDF.
That's all.
Neelima Rao

Joined: Feb 24, 2002
Posts: 26
getAbsolutePath returns the absolute i,e not relative path of the file or directory.
For example, the following code creates a file
'test' in the directory directly above the
current directory which is C:\java\io
File f1 = new File("..", "test.txt")
System.out.println( f1.getAbsolutePath() );
the canonical path is the same as the absolute path BUT all relative indicators . and .. are resolved
For example,
System.out.println( f1.getCanonicalPath() );
// '..' in absolute path is resolved
getPath converts the abstract pathname into a pathname string.
For example,
System.out.println( f1.getPath() );
Hope this helps......
Steven Wong
Ranch Hand

Joined: Mar 07, 2002
Posts: 295
Thanks a lot, guys.
Manish Hatwalne
Ranch Hand

Joined: Sep 22, 2001
Posts: 2591

In short, remember this -
1) getPath() returns whatever was passed to the onstructor.
2) getAbsolutePath() returns the current working directory path + whatever was passed to the constructor, as if it is just a plain string concatenation.
3)getCanonicalPath() works similar to getAbsolutePath() but it resolves . to current directory and .. to parent directory, and return the resulting path, much similar to the way relative URLs get resolved to absolute URLs.
- Manish
I agree. Here's the link:
subject: File Class
It's not a secret anymore!