Search code examples
javaunixposix

PosixFilePermission causing UnsupportedOperationException in java


I have a java code deployed in windows as well as unix system.I have to add file permission for moving the file to a specific directory(in unix).I am using PosixFilePermission for this.

                file1 = new File( expFilePath+ "/" + creationDate);
                file1.mkdir();
                Set<PosixFilePermission> perms = new HashSet<>();
                perms.add(PosixFilePermission.OWNER_READ);
                perms.add(PosixFilePermission.OWNER_WRITE);
                perms.add(PosixFilePermission.OWNER_EXECUTE);
                perms.add(PosixFilePermission.OTHERS_READ);
                perms.add(PosixFilePermission.OTHERS_WRITE);
                perms.add(PosixFilePermission.OTHERS_EXECUTE);
                perms.add(PosixFilePermission.GROUP_READ);
                perms.add(PosixFilePermission.GROUP_WRITE);
                perms.add(PosixFilePermission.GROUP_EXECUTE);
                try {
                    Files.setPosixFilePermissions(file1.toPath(), perms);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

The above code is running correctly in unix but causing a UnsupportedOperationException in windows m/c.I have to manually comment this piece of code while running the code in windows m/c.

Is there any way by which I can detect the underlying os type in java and execute this block of code conditionally?


Solution

  • If you have a Path object, you can use the Path.getFileSystem() method to obtain the underlying file system object. It has a FileSystem.supportedFileAttributeViews() method. If the file system supports POSIX file attributes (and permissions), the returned set will contain the string "posix".