Thursday, July 13, 2006

Finding Symbolic Links in Java

This time, I had to list all the files in my PC using Java. I wrote a java program and while running it, I got a error saying, "too many levels of symbolic links". I searched in Google, and found that, I can eliminate the symbolic links using the following code.

File system listing shows (b.txt -> a.txt).

File f = new File("b.txt");
System.out.println("Canonical : "+f.getCanonicalPath());
System.out.println("Absolute : "+f.getAbsolutePath());

Output :
Canonical : a.txt
Absolute : b.txt

Here, if both the path are not same, then the file pointed by Absolute path is a link or may be present inside a folder which is a link to another.

This didn't told me whether a file is sym link or not. coz, if the file is present inside a directory which is a link to another, then I this code will say that the file is a sym link.
ie. if dirB is a link to dirA and the file is present in dirA, then this code will tell me that the file is a sym link, which is not true.

But I will know that, there is a path without any sym links to access this file.

No comments: