Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create relative symlink in Java NIO.2?

Tags:

java

nio

In linux we can create relative symlinks.

 ln -s targetfile symlink

In java NIO.2

Files.createSymbolicLink(symlink, targetfile); 

this code not working with relative paths.

like image 647
hurelhuyag Avatar asked Sep 17 '15 07:09

hurelhuyag


2 Answers

Below is the code to give relative path while creating Symbolic links in order to make it accessible in cross platform environments.

Path source = Paths.get("D:\\A\\B\\C\\D\\E\\F\\G\\a.mp4"); // original file's absolute path
Path link = Paths.get("D:\\A\\B\\C\\D\\E\\F\\H\\I\\a.mp4"); // symbolic link's absolute path
Path relativeSrc = link.getParent().relativize(source); // relative path of original file from symbolic link

link.getParent().toFile().mkdirs(); // create the directory hierarchy if any folder is not available 
Files.createSymbolicLink(link, reativeSrc); // create symbolic link.

Hope this will help :)

like image 91
saurabh kedia Avatar answered Nov 12 '22 17:11

saurabh kedia


Files.createSymbolicLink(destination, targetDirectory.relativize(targetfile));

like image 29
caioquirino Avatar answered Nov 12 '22 19:11

caioquirino