Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

getCanonicalPath() vis - a- vis getAbsolutePath()

 
DD
Ranch Hand
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 66
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear Benoit,
Thank you very much for your explanation...it really helped
-Deb
 
Prasad Ballari
Ranch Hand
Posts: 149
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic