Tuesday, 2 May 2023

Check whether a file is symbolic link or not in Java

Files.isSymbolicLink method returns true if the file is a symbolic link; false if the file does not exist, is not a symbolic link, or it cannot be determined if the file is a symbolic link or not.

 

Signature

public static boolean isSymbolicLink(Path path)

 

I am going to test the application using a.txt, b.txt files.

$ ls -lart
total 0
drwxrwxrwt  29 root     wheel  928 May  3 10:13 ..
-rw-r--r--   1 krishna  wheel    0 May  3 10:13 a.txt
lrwxr-xr-x   1 krishna  wheel    5 May  3 10:13 b.txt -> a.txt
drwxr-xr-x   4 krishna  wheel  128 May  3 10:13 .

 

As you see above snippet, b.txt is a symbolic link point to a.txt.

 


Find the below working application.

 

SymbolicLinkCheckDemo.java

package com.sample.app.files;

import java.io.File;
import java.nio.file.Files;

public class SymbolicLinkCheckDemo {

	public static void main(String[] args) {
		String filePath1 = "/Users/Shared/examples/a.txt";
		String filePath2 = "/Users/Shared/examples/b.txt";

		boolean isFile1SymbolicLink = Files.isSymbolicLink(new File(filePath1).toPath());
		boolean isFile2SymbolicLink = Files.isSymbolicLink(new File(filePath2).toPath());
		
		System.out.println("isFile1SymbolicLink : " + isFile1SymbolicLink);
		System.out.println("isFile2SymbolicLink : " + isFile2SymbolicLink);
	}

}

 

Output

isFile1SymbolicLink : false
isFile2SymbolicLink : true

 

 

 

You may like

file and stream programs in Java

Check given path is a directory and not a symbolic link in Java

Convert InputStream to string

Write InputStream to a file in Java

File separator, separatorChar, pathSeparator, pathSeparatorChar in Java

Implement an Output stream that writes the data to two output streams

No comments:

Post a Comment