3

I've a directory on remote machine in which I have symbolic links pointing to actual files, and I am supposed to read the actual files given the symbolic link.

I can do it, if I can find the actual filePath, which is pointed to by the Symbolic Link.

I know that if we were using Java 7 we could do it using NIO2's classes (namely Path, Paths and Files), but we can't upgrade to JDK7 for several reasons.

The same thing I do not see in Java 6. What should be the work around for the same? I have already tried going through this but it didn't help.

Community
  • 1
  • 1
java_enthu
  • 2,279
  • 7
  • 44
  • 74
  • Try and execute `readlink -f thefile` on the remote host; a non zero exit status means the link has no valid target, otherwise it outputs the result on stdout. But doesn't `.getCanonicalFile()` work? – fge Mar 20 '14 at 09:13
  • Nope fge, getCanonicalFile doesn't work.It gives you the location of the symbolic link itself. About : readlink -f thefile could you elaborate please ? – java_enthu Mar 20 '14 at 09:20
  • What don't you understand exactly? – fge Mar 20 '14 at 09:26
  • readlink -f symLink doesn't return anything except canonicalPath of the symbolLink which points to itself not the actualfile location. – java_enthu Mar 20 '14 at 09:33
  • Sorry, that should be readlink -e – fge Mar 20 '14 at 09:35
  • ...and `getCanonicalPath()` not `getCanonicalFile()`. – mazaneicha Mar 20 '14 at 09:37
  • getCanonicalPath() will point to the location of the symLink. BTW : readLink -f link using java's runtime.exec. how do you get the return value ? – java_enthu Mar 20 '14 at 10:00

1 Answers1

3

I don't have enough reputation to comment, but I can give an answer. Strange.

This program demonstrates getCanonicalPath() and it does indeed resolve the symlink.

import java.io.*;

public class Test {
    public static void main(String[] args) throws IOException {
        File link = new File("testlink");
        System.out.println(link.getCanonicalPath());
    }
}

and running it produces:

[jon@dragon ~]$ ls -l testlink
lrwxrwxrwx. 1 jon jon 9 Apr 15 13:31 testlink -> Test.java
[jon@dragon ~]$ java Test
/home/jon/Test.java
Jon B
  • 471
  • 5
  • 8