Using Symbolic Links in Java

Using Symbolic Links in Java

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*;public class SymbolicLink{   public static void main(String args[])   {      SymbolicLink symbolicLink = new SymbolicLink();      symbolicLink.proceed();   }      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/");            try {         Files.createSymbolicLink(symbolicLinkName, soruceName);         System.out.println("SymbolicLink created for " + soruceName);      }catch (IOException ioe) {         System.err.println(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

After execution:

[root@mypc]# java SymbolicLinkSymbolicLink created for /home/sridhar/[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.javadrwxr-xr-x 2 root root   33 Jun 19 12:42 restrictedAccess

Executing for a second time results in a exception:

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

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist