How to get the current umask value from Java?

3.3k views Asked by At

I am running java 7 applications on unix machines. Is there a way to get the current umask value in pure java ?

In C I would use a combination of umask system calls, but I don't think I can call that in Java without resorting to JNI. Is there another approach ?

Edit: Here is a C example (from GUN libc docs):

      mode_t
      read_umask (void)
      {
        mode_t mask = umask (0);
        umask (mask);
        return mask;
      }
2

There are 2 answers

2
Ortwin Angermeier On

Can you clarify? Do you want to read the umask of the application(the current java process)? Or do you want to read the umask value of some files on the file system?

You can use NIO (the used code is from the javadocs) to get some file attributes, or you can execute a shell command, since the process created with Runtime.execute inherits the umask of it's creator process.

So you should be able to solve your problem without the use of JNI.

package test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.PosixFileAttributeView;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermissions;

public class Test {

    private static final String COMMAND = "/bin/bash -c umask -S";


    public static String getUmask() {
        final Runtime runtime = Runtime.getRuntime();
        Process process = null;
        try {
            process = runtime.exec(COMMAND);
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String umask = reader.readLine();
            if (process.waitFor() == 0)
                return umask;
        } catch (final IOException e) {
            e.printStackTrace();
        } catch (final InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
        return "";
    }

    public static void main(String[] args) throws IOException {
        /*
         * NIO
         */
        PosixFileAttributes attrs = Files.getFileAttributeView(Paths.get("testFile"), PosixFileAttributeView.class)
                .readAttributes();
        System.out.format("%s %s%n", attrs.owner().getName(), PosixFilePermissions.toString(attrs.permissions()));

        /*
         * execute shell command to get umask of current process
         */
        System.out.println(getUmask());

    }

}
1
James Liu On

A simple solution, if there is no Class/Method to get the umask, why don't you get it before call java and pass as a property?