Java 如何以编程方式更改文件权限?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/664432/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I programmatically change file permissions?
提问by Roy Rico
In Java, I'm dynamically creating a set of files and I'd like to change the file permissions on these files on a linux/unix file system. I'd like to be able to execute the Java equivalent of chmod
. Is that possible Java 5? If so, how?
在 Java 中,我正在动态创建一组文件,我想在 linux/unix 文件系统上更改这些文件的文件权限。我希望能够执行 Java 等价的chmod
. 那可能是Java 5吗?如果是这样,如何?
I know in Java 6 the File
object has setReadable()
/setWritable()
methods. I also know I could make a system call to do this, but I'd like to avoid that if possible.
我知道在 Java 6 中File
对象有setReadable()
/setWritable()
方法。我也知道我可以进行系统调用来做到这一点,但如果可能的话,我想避免这种情况。
采纳答案by erickson
Full control over file attributes is available in Java 7, as part of the "new" New IO facility (NIO.2). For example, POSIX permissions can be set on an existing file with setPosixFilePermissions()
,or atomically at file creation with methods like createFile()
or newByteChannel()
.
作为“新”新 IO 工具 ( NIO.2) 的一部分,Java 7 中提供了对文件属性的完全控制。例如,POSIX权限可以在与现有的文件设置setPosixFilePermissions()
,在文件创建与类似的方法或原子createFile()
或newByteChannel()
。
You can create a set of permissions using EnumSet.of()
, but the helper method PosixFilePermissions.fromString()
will uses a conventional format that will be more readable to many developers. For APIs that accept a FileAttribute
, you can wrap the set of permissions with with PosixFilePermissions.asFileAttribute()
.
您可以使用 来创建一组权限EnumSet.of()
,但辅助方法PosixFilePermissions.fromString()
将使用传统格式,这对许多开发人员来说更具可读性。对于接受 的 API FileAttribute
,您可以使用 将权限集包装起来PosixFilePermissions.asFileAttribute()
。
Set<PosixFilePermission> ownerWritable = PosixFilePermissions.fromString("rw-r--r--");
FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(ownerWritable);
Files.createFile(path, permissions);
In earlier versions of Java, using native code of your own, or exec
-ing command-line utilities are common approaches.
在 Java 的早期版本中,使用您自己的本机代码或exec
-ing 命令行实用程序是常见的方法。
回答by Marty Lamb
In addition to erickson's suggestions, there's also jna, which allows you to call native libraries without using jni. It's shockingly easy to use, and I've used it on a couple of projects with great success.
除了 erickson 的建议之外,还有jna,它允许您在不使用 jni 的情况下调用本机库。它非常容易使用,我已经在几个项目中使用它并取得了巨大成功。
The only caveat is that it's slower than jni, so if you're doing this to a very large number of files that might be an issue for you.
唯一需要注意的是,它比 jni 慢,因此如果您对大量文件执行此操作,这可能对您来说是个问题。
(Editing to add example)
(编辑以添加示例)
Here's a complete jna chmod example:
这是一个完整的 jna chmod 示例:
import com.sun.jna.Library;
import com.sun.jna.Native;
public class Main {
private static CLibrary libc = (CLibrary) Native.loadLibrary("c", CLibrary.class);
public static void main(String[] args) {
libc.chmod("/path/to/file", 0755);
}
}
interface CLibrary extends Library {
public int chmod(String path, int mode);
}
回答by Erel Segal-Halevi
You can use the methods of the File class: http://docs.oracle.com/javase/7/docs/api/java/io/File.html
您可以使用 File 类的方法:http: //docs.oracle.com/javase/7/docs/api/java/io/File.html
回答by bob
for windows 7 with nio 2.0:
对于带有 nio 2.0 的 Windows 7:
public static void main(String[] args) throws IOException
{
Path file = Paths.get("c:/touch.txt");
AclFileAttributeView aclAttr = Files.getFileAttributeView(file, AclFileAttributeView.class);
System.out.println(aclAttr.getOwner());
for(AclEntry aclEntry : aclAttr.getAcl()){
System.out.println(aclEntry);
}
System.out.println();
UserPrincipalLookupService upls = file.getFileSystem().getUserPrincipalLookupService();
UserPrincipal user = upls.lookupPrincipalByName(System.getProperty("user.name"));
AclEntry.Builder builder = AclEntry.newBuilder();
builder.setPermissions( EnumSet.of(AclEntryPermission.READ_DATA, AclEntryPermission.EXECUTE,
AclEntryPermission.READ_ACL, AclEntryPermission.READ_ATTRIBUTES, AclEntryPermission.READ_NAMED_ATTRS,
AclEntryPermission.WRITE_ACL, AclEntryPermission.DELETE
));
builder.setPrincipal(user);
builder.setType(AclEntryType.ALLOW);
aclAttr.setAcl(Collections.singletonList(builder.build()));
}
回答by Vlad
for Oralce Java 6:
对于 Oralce Java 6:
private static int chmod(String filename, int mode) {
try {
Class<?> fspClass = Class.forName("java.util.prefs.FileSystemPreferences");
Method chmodMethod = fspClass.getDeclaredMethod("chmod", String.class, Integer.TYPE);
chmodMethod.setAccessible(true);
return (Integer)chmodMethod.invoke(null, filename, mode);
} catch (Throwable ex) {
return -1;
}
}
works under solaris/linux.
在solaris/linux下工作。
回答by ihadanny
Apache ant chmod (not very elegant, adding it for completeness) credit shared with @msorsky
与@msorsky 共享的 Apache ant chmod(不是很优雅,添加它是为了完整性)
Chmod chmod = new Chmod();
chmod.setProject(new Project());
FileSet mySet = new FileSet();
mySet.setDir(new File("/my/path"));
mySet.setIncludes("**");
chmod.addFileset(mySet);
chmod.setPerm("+w");
chmod.setType(new FileDirBoth());
chmod.execute();
回答by PixelsTech
Prior to Java 6, there is no support of file permission update at Java level. You have to implement your own native method or call Runtime.exec()
to execute OS level command such as chmod.
在 Java 6 之前,不支持 Java 级别的文件权限更新。您必须实现自己的本机方法或调用Runtime.exec()
以执行操作系统级别的命令,例如chmod。
Starting from Java 6, you can useFile.setReadable()/File.setWritable()/File.setExecutable()
to set file permissions. But it doesn't simulate the POSIX file system which allows to set permission for different users. File.setXXX() only allows to set permission for owner and everyone else.
从 Java 6 开始,您可以使用File.setReadable()/File.setWritable()/File.setExecutable()
来设置文件权限。但它没有模拟允许为不同用户设置权限的 POSIX 文件系统。File.setXXX() 只允许为所有者和其他所有人设置权限。
Starting from Java 7, POSIX file permission is introduced. You can set file permissions like what you have done on *nix systems. The syntax is :
从 Java 7 开始,引入了 POSIX 文件权限。您可以像在 *nix 系统上所做的那样设置文件权限。语法是:
File file = new File("file4.txt");
file.createNewFile();
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
Files.setPosixFilePermissions(file.toPath(), perms);
This method can only be used on POSIX file system, this means you cannot call it on Windows system.
此方法只能在 POSIX 文件系统上使用,这意味着您不能在 Windows 系统上调用它。
For details on file permission management, recommend you to read this post.
有关文件权限管理的详细信息,建议您阅读此帖子。
回答by jan.supol
There is an example class on Oracle Docswhich works very much similar to the UNIX chmod. It works with java se 7+ though.
Oracle Docs 上有一个示例类,其工作方式与 UNIX chmod 非常相似。不过,它适用于 java se 7+。
回答by Anuj Dhiman
simple java code for change file permission in java
String path="D:\file\read.txt";
File file=new File(path);
if (file.exists()) {
System.out.println("read="+file.canRead());
System.out.println("write="+file.canWrite());
System.out.println("Execute="+file.canExecute());
file.setReadOnly();
}
Reference : how to change file permission in java
回答by Apoorv Chourasiya
If you want to set 777 permission to your created file than you can use the following method:
如果要为创建的文件设置 777 权限,则可以使用以下方法:
public void setPermission(File file) throws IOException{
Set<PosixFilePermission> perms = new HashSet<>();
perms.add(PosixFilePermission.OWNER_READ);
perms.add(PosixFilePermission.OWNER_WRITE);
perms.add(PosixFilePermission.OWNER_EXECUTE);
perms.add(PosixFilePermission.OTHERS_READ);
perms.add(PosixFilePermission.OTHERS_WRITE);
perms.add(PosixFilePermission.OTHERS_EXECUTE);
perms.add(PosixFilePermission.GROUP_READ);
perms.add(PosixFilePermission.GROUP_WRITE);
perms.add(PosixFilePermission.GROUP_EXECUTE);
Files.setPosixFilePermissions(file.toPath(), perms);
}