如何以编程方式更改文件权限? [英] How do I programmatically change file permissions?

查看:32
本文介绍了如何以编程方式更改文件权限?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Java 中,我正在动态创建一组文件,我想在 linux/unix 文件系统上更改这些文件的文件权限.我希望能够执行 chmod 的 Java 等价物.那可能是Java 5吗?如果是,怎么办?

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 6 中 File 对象有 setReadable()/setWritable() 方法.我也知道我可以通过系统调用来做到这一点,但如果可能的话,我想避免这种情况.

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 7 中可以完全控制文件属性,作为新"新 IO 工具 (NIO.2).例如,可以使用 setPosixFilePermissions(), 或使用 createFile()newByteChannel().

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().

您可以使用 EnumSet.of() 创建一组权限,但是辅助方法 PosixFilePermissions.fromString() 将使用传统格式对许多开发人员来说将更具可读性.对于接受 FileAttribute 的 API,您可以使用 PosixFilePermissions.asFileAttribute().

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().

Set<PosixFilePermission> ownerWritable = PosixFilePermissions.fromString("rw-r--r--");
FileAttribute<?> permissions = PosixFilePermissions.asFileAttribute(ownerWritable);
Files.createFile(path, permissions);

在 Java 的早期版本中,使用您自己的本机代码或 exec-ing 命令行实用程序是常见的方法.

In earlier versions of Java, using native code of your own, or exec-ing command-line utilities are common approaches.

这篇关于如何以编程方式更改文件权限?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆