Browse DevX
Sign up for e-mail newsletters from DevX


Tip: Using Symbolic Links in Java

Learn about how to keep your source code safe and the original location hidden with Symbolic links.




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Symbolic links are a useful entity, with which you can introduce some kind of encapsulation. The Symbolic link can be created in a secure environment (ex: DMZ) where users can access with valid credentials.

This helps us to keep the real source safe and the original location hidden. The exposed location, in reality, maybe a virtual path that can be created based on various parameters such as login session, user credentials, etc.

Sample code:

import java.nio.file.*;
import java.io.*;

public class SymbolicLink
   public static void main(String args[])
      SymbolicLink symbolicLink = new SymbolicLink();
   private void proceed()
      //You can use a secure path here that may be exposed to external users, who may be autorized to perform changes
      //The path is referring to restrictedAccess folder and this folder can be provided access so that external users can access
      Path symbolicLinkName = Paths.get("/home/sridhar/restrictedAccess/SymLnkForSourceFile");
      //This is the source file for which the link is being established
      Path soruceName = Paths.get("/home/sridhar/SymbolicLink.java");
      try {
         Files.createSymbolicLink(symbolicLinkName, soruceName);
         System.out.println("SymbolicLink created for " + soruceName);
      }catch (IOException ioe) {


Expected output:

Before execution:
[root@mypc]# ls -lrt
-rw-r--r-- 1 root root 1078 Jun 19 12:41 SymbolicLink.class
-rw-r--r-- 1 root root 1274 Jun 19 12:41 SymbolicLink.java

After execution:

[root@mypc]# java SymbolicLink
SymbolicLink created for /home/sridhar/SymbolicLink.java
[root@mypc]# ls -lrt
-rw-r--r-- 1 root root 1078 Jun 19 12:41 SymbolicLink.class
-rw-r--r-- 1 root root 1274 Jun 19 12:41 SymbolicLink.java
drwxr-xr-x 2 root root   33 Jun 19 12:42 restrictedAccess

Executing for a second time results in a exception:

[root@mypc]# java SymbolicLink
java.nio.file.FileAlreadyExistsException: /home/sridhar/restrictedAccess/SymLnkForSourceFile



Visit the DevX Tip Bank


Sridhar M S. is a Java developer from Bangalore, India. He holds a master's degree in Computer Science.
Thanks for your registration, follow us on our social networks to keep up-to-date