java 改变文件权限_Java文件权限

java 改变文件权限

Java File class contains methods to check file permissions for the application user. They also have some methods to set file permissions for the user and everybody else.

Java File类包含用于检查应用程序用户的文件许可权的方法。 他们还有一些方法可以为用户和其他所有人设置文件权限。

Java文件权限 (Java File Permissions)

Here is a simple java program using File class permission methods. We will first check the file permissions for the user. Later on, we will change the file permissions for the application user and then for all the other users too.

这是一个使用File类权限方法的简单Java程序。 我们将首先检查用户的文件权限。 稍后,我们将更改应用程序用户的文件权限,然后再更改所有其他用户的文件权限。

package com.journaldev.files;

import java.io.File;

public class JavaFilePermissions {

    public static void main(String[] args) {
        File file = new File("/Users/pankaj/run.sh");
        //check file permissions for application user
        System.out.println("File is readable? "+file.canRead());
        System.out.println("File is writable? "+file.canWrite());
        System.out.println("File is executable? "+file.canExecute());
        //change file permissions for application user only
        file.setReadable(false);
        file.setWritable(false);
        file.setExecutable(false);
        //change file permissions for other users also
        file.setReadable(true, false);
        file.setWritable(true, false);
        file.setExecutable(true, true);
    }

}

Below image shows the output produced by the above application.

下图显示了以上应用程序产生的输出。

Note that setting File permissions is not versatile and if you are working on Java 7, you should use Java PosixFilePermission to set file permissions.

请注意,设置文件权限不是通用的,如果您正在使用Java 7,则应使用Java PosixFilePermission设置文件权限。

Also these File set permission methods return false if they are not able to set the file permissions. This can happen due to user privilege. For example, if I change the owner of my sample file to root, then all the set file permission method calls return false.

同样,如果这些文件集权限方法无法设置文件权限,则它们将返回false 。 由于用户特权,可能会发生这种情况。 例如,如果我将示例文件的所有者更改为root,则所有设置文件权限方法调用都将返回false。

That’s all for java file permissions, how to check file permissions and how to set file permissions in java.

这就是Java文件权限,如何检查文件权限以及如何在Java中设置文件权限的全部内容。

Reference: https://docs.oracle.com/javase/8/docs/api/java/io/File.html#setReadable-boolean-

参考: https : //docs.oracle.com/javase/8/docs/api/java/io/File.html#setReadable-boolean-

翻译自: https://www.journaldev.com/858/java-file-permissions

java 改变文件权限

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值