How to manage Linux file permissions in Java?

半腔热情 提交于 2019-12-10 10:09:28

问题


Is there any mechanism to get and set the file/directory permissions?

For example, I want to show the permisssions of a file in a shell way:

-rwxr-xr--

Is it possible to do this using Java?

  • I know that there are some methods in the File class to know if the file canExecute, canRead and canWrite, but AFAIK this info is for the current user only. I need to know the whole octal number, for example 755, so I need to get it from the user, from group and from others.
  • I know that Java7 brings Posix operations, but how could do this using a smaller JRE?
  • I would like not to use a command like ls, or chmod.

回答1:


If you can use external libraries, there are several:

  • JPosix
  • Posix for java
  • jnr-posix

If an entire library seems a hassle, creating a JNI wrapper that calls the lstat C function and returns the access mode takes you about 10 minutes. Here's a tutorial that creates such a wrapper for the isatty and ttyname functions.




回答2:


As you say, in Java7, the JVM supports it, so you have a guarantee that this can be done portably in all OSs (because the JVM implementation takes care of it). Under Java7, you'd have to use a native library per OS you want to support. This is potentially even dirtier than executing chmod



来源:https://stackoverflow.com/questions/15568629/how-to-manage-linux-file-permissions-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!