Creating a symbolic link with Java
Asked Answered
C

1

17

I'm having trouble creating a symbolic link to a directory in Java. I'm using the createSymbolicLink() method from the Files class: http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html

Absolute paths:

  • Target: /some/path/target
  • Link: /some/path/xxx/linkname

I would expect that a link in the directory /some/path/xxx/ is created to the folder /some/path/target, but instead a link from /some/path/xxx/linkname to /some/path/xxx/target is created. I just can't figure out what I'm doing wrong.

When I create a link from /some/path/linkname to /some/path/target, everything works as expected.

Any help is greatly appreciated.

EDIT: Here's my code:

Path records = Paths.get(Properties.getProperty("records.path"));
Path recordsLink = Paths.get(Properties.getProperty("webserver.root") + System.getProperty("file.separator") + records.getFileName());
try {
    Files.createSymbolicLink(recordsLink, records);
} catch (IOException e) {
    e.printStackTrace();
}

The "records.path" and "webserver.root" are both relative paths.

Actually I just found a solution to the problem: It works if I do this:

records = records.toAbsolutePath();

I assumed the createSymbolicLink() will use absolute paths to create the links, which was wrong.

Chatterton answered 29/7, 2013 at 14:19 Comment(6)
Can you post your code ?Hardship
I found a solution. See edited post.Chatterton
Please do not edit questions to put answers there. Even if you found the answer to your question yourself do put it in a proper answer.Gere
I would have, but with less than 10 reputation, I have to wait 10 hours before I can post an answer to my own question.Chatterton
10 hours have passed :)Confer
I believe the root of this problem is the location of the cwd (current working directory).. Which under java can sometimes be anywhere. If one wanted to use a relative path; you need to cd to the folder where you want the link. See: Java Change File Working DirectoryTyeshatyg
C
10

I found the solution to the problem: It works if I do this:

records = records.toAbsolutePath();

I assumed createSymbolicLink() will use absolute paths to create the links, which was wrong.

Chatterton answered 27/11, 2014 at 18:43 Comment(1)
Not sure why you're converting from path to string to path -- records = records.toAbsolutePath() is equivalent.Harhay

© 2022 - 2024 — McMap. All rights reserved.