Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if filesystem supports links and symlinks in Java

The Files class introduced in Java 7 has methods for handling links and symlinks but only as optional operations.

Is there any way of determining at runtime if a file system supports these operations before actually invoking the respective methods or do I need to call them and then catch the exception?

Classes like FileSystem or FileStore do not seem to contain anything in that regard (or I overlooked it).

like image 352
shutefan Avatar asked Oct 02 '22 10:10

shutefan


1 Answers

I don't see any general approach that will work without relying on an UnsupportedOperationException or some other exception.

You could use a heuristic that assumes that only subclasses of BasicFileAttributesView support symbolic linking.


Note: The approach below will not work because FileAttributeViews and file attributes are not the same concept:

I did not get isSymbolicLink as one of the supported attributes with the following code on OS X 10.8.4:

package com.mlbam.internal;

import java.nio.file.Files;
import java.nio.file.FileStore;
import java.nio.file.FileSystems;
import java.nio.file.Paths;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class MainClass {
    private static final Logger LOG = LoggerFactory.getLogger(MainClass.class);
    public static void main(String[] args) {
        try {
            System.out.println("FileStore.supportsFileAttributeView('isSymbolicLink'): " 
                + Files.getFileStore(Paths.get("/")).supportsFileAttributeView("isSymbolicLink"));
            // Got: FileStore.supportsFileAttributeView('isSymbolicLink'): false
            System.out.println(FileSystems.getDefault().supportedFileAttributeViews());
            // Got: [basic, owner, unix, posix]
        } catch (Exception e) {}
    }
}

Original Answer:

If you have an instance of FileStore, you can use FileStore.supportsFileAttributeView("isSymbolicLink")

Or, if you have an instance of FileSystem, you can check that resulting Set<String> from FileSystem.supportedFileAttributeViews() contains the String "isSymbolicLink".


You can get the FileStore associated with a Path using Files.getFileStore(Path)

One way of getting the FileSystem is via FileSystems.getDefault()


like image 71
yegeniy Avatar answered Oct 13 '22 11:10

yegeniy