一个policy权限控制例子

首先在项目根目录创建一个test.txt空文件,执行下面的代码

public class JavaPolicyTest {
    public static void main(String[] args) throws IOException {
//      注释1:  System.setProperty("java.security.policy", "test.policy");
//      注释2: System.setSecurityManager(new SecurityManager());
        File file = new File("test.txt");
        try {
            read(file);
            System.out.println("file read ok");
        } catch (Throwable e) {
            System.out.println(e.getMessage());
        }

        try {
            write(file);
            System.out.println("file write ok");
        } catch (Throwable e) {
            System.out.println(e.getMessage());
        }
    }

    private static void read(File file) throws Throwable {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))){
            String temp;
            while ((temp = reader.readLine()) != null) {
                System.out.println("read-->" + temp);
            }
        }
    }

    private static void write(File file) throws Throwable {
        FileWriter fw = new FileWriter(file,true);
        fw.write("hello world \r\n");
        System.out.println("write -> hello world");
        fw.flush();
        fw.close();
    }
}
情况1:

直接运行,最后会输出

file read ok
write -> hello world
file write ok

情况2:

把上面的注释2打开,再执行,输出如下:

access denied (“java.io.FilePermission” “test.txt” “read”)
access denied (“java.io.FilePermission” “test.txt” “write”)

情况3:

接下来在项目根目录下创建一个test.policy文件,内容如下:

grant codeBase "file:${user.dir}/-" {
    permission java.io.FilePermission "${user.dir}/test.txt","read,write";
};

表示在项目根目录下的代码,拥有对test.txt文件的读写权限

接着把注释1打开再执行,输出如下:

read–>hello world
file read ok
write -> hello world
file write ok

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值