We have been exploring the NIO enhancements in Java 7 and in this post I will explain about creating links- Hard links and Soft links in Java. And this feature is part of Java 7.
also read:
A link is kind of substitute name to access a particular file/directory, something like an alias to the file/directory. This way it allows us to refer to a file/directory by more than one name. There are 2 types of links that can be created:
- Symbolic Links: These links refer to the file/directory path. And using these links can be used to directly operate on the path they refer to. In my daily work I use a lot of symbolic links and they are really flexible. In this case if the file to which the link refers to is deleted, the link continues to exist but it is not a valid link.
- Hard Links: These links are more stricter than symbolic links which refer to the physical location of the file. If the content of the original file is changed, the link also gets updated whereas if the original file is deleted, the link continues to exist and is valid file.
Creating Symbolic Links in Java
Not all operating systems support creating symbolic links. The program I tried on Windows couldn’t create a symbolic link. But for creating symbolic link we make use of the Files.createSymbolicLink method which takes the link path as well as the target path, where both link and target are instances of type Path.
Creating Hard links in Java
On Windows I was able to create the Hard links and for this we make use of Files.createLink method which takes in link path and the target path.
Lets look at the example where both soft link and hard links are created:
Note: I tried this sample on Windows and Linux, but you can get better results in Linux, because I am not sure how to list the links in Windows.
public class LinkTest { public static void main(String[] args) throws IOException { Path file1 = Paths.get("test1"); System.out.println(file1.toRealPath()); Path hLink = Paths.get("test1.hLink"); Path sLink = Paths.get("test1.symLink"); try{ Files.createSymbolicLink(sLink, file1); }catch(UnsupportedOperationException ex){ System.out.println("This OS doesn't support creating Sym links"); } try{ Files.createLink(hLink, file1); System.out.println(hLink.toRealPath()); }catch(UnsupportedOperationException ex){ System.out.println("This OS doesn't support creating Sym links"); } } }
Pro Java 7 NIO.2 addresses the three primary elements that offer new input/output (I/O) APIs in Java 7, giving you the skills to write robust, scalable Java applications.