4

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?

Sumit Ghosh
  • 484
  • 4
  • 13
  • 36
  • 1
    If you want to detect the OS, you can check https://stackoverflow.com/questions/3282498/how-can-i-detect-a-unix-like-os-in-java. Then, if you want to set similar permision in Windows, then here is the link https://www.journaldev.com/855/how-to-set-file-permissions-in-java-easily-using-java-7-posixfilepermission – sayboras Nov 14 '17 at 06:58

1 Answers1

5

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".

Florian Weimer
  • 32,022
  • 3
  • 48
  • 92