I need to set the permission to read a file to a specific user of the operating system, how can I do this in Java?
Edit: The file will be created with permissions just to the user running the application, than it needs to set read permission to a single user, other users will 开发者_Python百科not have the permissions to read the file.
Use the methods setExecutable, setReadable, and setWritable in java.io.File. You can use these to change any permission bit of a file you own. Direct link: http://download.oracle.com/javase/6/docs/api/java/io/File.html#setReadable%28boolean%29. Testing this on MacOSX revels that only the user read value is changed. When program
import java.io.File;
public class Test
{
public static void main(String[] args)
{
File f = new File("test.txt");
f.setReadable(true);
}
}
the folloiwng happens.
$ touch test.txt
$ chmod 000 test.txt
$ javac Test.java
$ java Test
$ ls -l test.txt
-r-------- 1 morrison staff 0 Jun 7 13:28 test.txt
If you're targetting Windows Vista/7, build your JAR as EXE and embed a manifest requesting for Admin rights. If it's just an I/O problem, use the default File methods setReadable, setWritable, setExecutable :)
In regards to making the permissions for a single user, start with using ncmathsadist's code to add read permissions, then change the owner of the file to whoever needs access.
I found in the Ant source code they use for the change-owner task. For unix this can be found in the Ant source tree at org/apache/tools/ant/taskdefs/optional/unix/Chown.java. You might be able to include this and use it as an API call to change the user programmatically.
if you want to change file permissions on old Java versions like Java 5, you can use this:
Runtime.getRuntime().exec("chmod 000 " + PATH + fileName);
on windows you'll have to replace chmod with the appropriate CACLS.exe command syntax
精彩评论