13

I'm new to Java. Where is umask exposed in the api?

Reddy
  • 8,737
  • 11
  • 55
  • 73
eeee
  • 139
  • 1
  • 1
  • 3

4 Answers4

13

You can't fiddle with the umask directly, since Java is an abstraction and the umask is POSIX-implementation specific. But you have the following API:

File f;
f.setExecutable(true);
f.setReadable(false);
f.setWritable(true);

There are some more APIs available, check the docs.

If you must have direct access to the umask, either do it via JNI and the chmod() syscall, or spawn a new process with exec("chmod").

Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
  • Hm interesting, thanks. I guess I can use JNI to call umask(2), then? – eeee Jul 04 '10 at 16:58
  • @eeee sure, but you'd have to deploy your JNI module to all platforms you want to support, as it's almost by definition platform dependent. – extraneon Jul 04 '10 at 17:04
  • @extraneon yes, of course. To be honest I'm very surprised that no one has made a module for Java exposing all the posix interfaces. I mean, that can't be right -- right? How do people perform system activities in java without this kind of thing? – eeee Jul 04 '10 at 23:21
  • @eeee New APIs for this are coming in Java 7 (which is not out yet), in the package `java.nio.file`. – Jesper Jul 05 '10 at 07:03
  • to be precise: in the package `java.nio.file.attribute`. – Jesper Jul 05 '10 at 07:35
  • @eeee what's wrong with exec("chmod 777 yourfilename")? Or is the code section doing this extremely performance critical? – Alderath Oct 08 '12 at 09:03
  • @eeee even before java 7, sun(oracle) released a library called JNA that allows you to directly call into any native code including glibc. With it, they also have a prebuilt wrapper around all posix functions. And JNA supports any platform that is known to run a JVM. –  May 31 '20 at 18:47
1
import java.nio.file.Files
import java.nio.file.attribute.PosixFilePermission

File file = new File("/some/path") 
Files.setPosixFilePermissions(file.toPath(), [
                PosixFilePermission.OWNER_READ,
                PosixFilePermission.OWNER_WRITE
            ].toSet())
Ich
  • 1,350
  • 16
  • 27
1

Another approach is to use a 3rd-party Java library that exposes POSIX system calls; e.g.

The problem with this approach is that it is intrinsically non-portable (won't work on a non-POSIX compliant platform), and requires a platform-specific native library ... and all that that entails.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

java.nio.file.attribute.PosixFileAttributes in Java SE 7.

Tom Hawtin - tackline
  • 145,806
  • 30
  • 211
  • 305