I create a folder in my java program (running on linux) with mkdirs() function of File object. The problem is that the folder gets only read permissions for the group. I nee
OK this is not a java solution and definitely not portable.
Since you mention that you are linux, probably you can think of checking the "umask" settings and setting it appropriately (to have directories created with group write permissions) and then launching your java program.
A very simple solution for this is:
file.setExecutable(true, false);
file.setReadable(true, false);
file.setWritable(true, false);
In above code, file is a File object.
When you are creating a file set these permissions to a file setExecutable(true)
will allow you to set that file as Executable
for owner only. If you add one more parameter which I have added in above code file.setExecutable(true, false);
will make Executable
false
for owner only, that means it will set permissions to all group / world.
Tested and working on Debian and Windows XP.
Java nio can help with posix file attributes: https://docs.oracle.com/javase/8/docs/api/java/nio/file/attribute/PosixFileAttributeView.html
Path path = ...
Set<PosixFilePermission> perms =
EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ, GROUP_WRITE);
Files.createFile(path, PosixFilePermissions.asFileAttribute(perms));
I suspect (unless/until someone posts an answer to the contrary) that there's no way to do this in Java's standard library, because POSIX group permissions (the rwxrwxrwx kind you're used to) are not cross-platform. Java 6 will let you set owner permissions or global permissions, but (as far as I can tell) not group permissions. If you really must do it, try using Runtime.exec("chmod g+w directory")
, but it might be a good idea stylistically to wrap it in a method like setGroupWritable()
.
On java 6, there are methods that allow you to do this, like setwriteable(). On previous versions of java, you'll have to access the command line to do a chmod command.
Java 6 SE File Class Doc.
EDIT: Woops, I'm completely wrong; I failed to notice that you wanted group permissions specifically. Those don't appear to be settable without Runtime.exec().
@David: You're right.
Another thought: if you have a lot of files to change, how about writing a shell script and calling that from runtime.exec()?