Sunday, 8 January 2023

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

Below snippet return true, if the filePath is a regular file and not a symbolic link.

Files.isRegularFile(filePath, LinkOption.NOFOLLOW_LINKS);

 

Let’s experiment it with below example.

$ls -lart
total 8
-rw-r--r--   1 krishna  wheel   12 Jan  7 21:11 a.txt
drwxrwxrwt  17 root     wheel  544 Jan  8 17:53 ..
lrwxr-xr-x   1 krishna  wheel    5 Jan  8 18:03 a_link.txt -> a.txt
drwxr-xr-x   7 krishna  wheel  224 Jan  8 18:03 .

As you see above snippet

1.   a.txt is a regular file

2.   a_link.txt is a symbolic link point to the regular file a.txt

 

Find the below working application.

 


RegularFileCheck.java

package com.sample.app.files;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.util.Objects;

public class RegularFileCheck {

	public static boolean isFile(final String filePath) {
		Objects.requireNonNull(filePath);
		return isFile(new File(filePath));
	}

	public static boolean isFile(final File file) {
		Objects.requireNonNull(file);
		return isFile(file.toPath());
	}

	public static boolean isFile(final Path filePath) {
		Objects.requireNonNull(filePath);
		return Files.isRegularFile(filePath, LinkOption.NOFOLLOW_LINKS);
	}

	public static void main(String[] args) {
		final String file1 = "/Users/Shared/filePrograms/a.txt";
		final String file2 = "/Users/Shared/filePrograms/a_link.txt";

		System.out.println("Is '" + file1 + "' regular file ? " + isFile(file1));
		System.out.println("Is '" + file2 + "' regular file ? " + isFile(file2));
	}
}

Output

Is '/Users/Shared/filePrograms/a.txt' regular file ? true
Is '/Users/Shared/filePrograms/a_link.txt' regular file ? false


 

You may like

file and stream programs in Java

Touch the file in Java (Update the file timestamp)

Get POSIX file attributes in Java

Get file basic file attributes in Java

check whether a file is executable or not in Java

Check whether a directory has some files or not

No comments:

Post a Comment