wood burning stoves*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes getCanonicalPath() vis - a- vis getAbsolutePath() 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 "getCanonicalPath() vis - a- vis getAbsolutePath()" Watch "getCanonicalPath() vis - a- vis getAbsolutePath()" New topic
Author

getCanonicalPath() vis - a- vis getAbsolutePath()

DD
Ranch Hand

Joined: Oct 13, 2000
Posts: 66
Hi all,
could anybody kindly help me out with understanding the difference between the two methods above?
I am really getting confused!
thanks in advance
-Deb
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
The canonical form ensure that you can compare safely two file paths, i.e if they point to the same file or directory, they will be equal.
Let's consider, we have the following directory tree:
<PRE>
C:\
|
+--jdk1.3
|
+--projects
|
+--test
</PRE>
You are located in the test directory. Now to get a File object on the parent directory, you can either write:
<PRE>
File f = new File ("C:\jdk1.3\projects");
</PRE>
or
<PRE>
File f = new File ("..");
</PRE>
The getCanonicalPath() method will always give you the same directory, i.e. <code>"C:\jdk1.3\projects"</code>. But the result from getAbsolutePath will be different for the second form, i.e. <code>"C:\jdk1.3\projects\test\.."</code>.
The following code will help you to test it:
<PRE>
public class test
{
public static void main(String args[])
{
try
{
File f = new File("..");
System.out.println("Canonical Path: " + f.getCanonicalPath());
System.out.println("Absolute Path: " + f.getAbsolutePath());
}
catch (IOException e) {}
}
}
</PRE>
will output the following:
<PRE>
Canonical Path: C:\jdk1.3\projects
Absolute Path: C:\jdk1.3\projects\test\..
</PRE>
Regards
Beno�t
DD
Ranch Hand

Joined: Oct 13, 2000
Posts: 66
Dear Benoit,
Thank you very much for your explanation...it really helped
-Deb
Prasad Ballari
Ranch Hand

Joined: Sep 23, 2000
Posts: 149
Beno�t,
Thanks for your answer.Will u please tell me the need of getCanonicalPath(). and where it is used?
Regards
Prasad

------------------
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
It is especially interesting to use the getCanonicalPath method when you have to display the path name on screen. As in my previous mail, it is always better to display this:
<PRE>Path: C:\jdk1.3\projects</PRE>
instead of this:
<PRE>Path: C:\jdk1.3\projects\test\..</PRE>
Cheers,
Beno�t
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: getCanonicalPath() vis - a- vis getAbsolutePath()
 
Similar Threads
Calculating historical dates
Merits of JBuilder - question to users.
How windows CE , Symbian compared with J2ME ?
How good is JWhiz?
java.lang package