Hi All :
I want to give permissions mode value "777" to image file using java code. How can i give that using java?. Because i cant delete the image with default permission mode "664". Please help me
views:
1070answers:
4Its a part of the NIO package. You can do it via java.nio.file.attribute.PosixFilePermission.
This is only in Java 1.7 though, it has been a known issue for a while now.
You can use the 'exec' method to run an external command to do the chmod.
Runtime.getRuntime().exec( "chmod 777 myfile" );
You can create a File object associated with the file then change permissions using setExecutable, setReadable, and setWritable. Naturally, these operations will fail if your program doesn't have permission to change access permissions for the file.
Unfortunately Java gives few grab to the system file properties, because it would break the gold rule of java "write once, run everywhere".
Indeed when you write that you want to put a 777 access to the file, it obviously means that you're under unix. But what such a request would have meant under Windows for example ?
So it shouldn't be a surprise that to address specific OS topics, you would have to use specific functions. That's the price to pay when using a language that claims (with strong reasons) being "platform independent"
The safer way would be to use a JNI library that implements exactly what you want. A simple but dirty and hazardous way would be to using a Runtime.getRuntime().exec("chmod 777 myFile").
Why hazardous ? In fact, what happens when one call such exec("blahblah") ?
The unix process running your java program forks; the "duplicated" process then execs a shell (ksh ? csh ? bash ?? it depends on your unix configuration), that tries to understand and run your "blahblah" sentence.
If your jvm is actually using 500 MB, the forked process would be the same size when it starts...
Then the shell will start with the same "shell context" than the java process, that is to say the same PATH, aliases and so on. Even "chmod" could have been aliased, so it would be better to call the full path for chmod (/bin/chmod, /usr/bin/chmod... it depends on the unix flavour...).
During the shell execution, your java program is freezed, and you have no way to unfreeze it if for any reason the shell hangs.
And finally, it's not even sure the unix owner of the java program has sufficient rights to change such informations on the file (he could be allowed to create the file, but not to change user level rights, for example).
Maybe you try to handle at the java level a problem that should be addressed at the OS level ?