简体   繁体   English

在Java中检查文件夹权限的问题

[英]Issue with checking permission of a folder in java

I am creating simple function to check weather I have write/delete permission to a folder 我正在创建简单的功能来检查天气,我具有对文件夹的写入/删除权限

I want to know whether the operating system will allow writing into the folder or not ? 我想知道操作系统是否允许写入文件夹?

public static String PermissionCheck(String FilePath) {
    //File f = new File(FilePath);
    String actions = "read,write";
    try 
    {
      AccessController.checkPermission(new FilePermission(FilePath, actions));
      return ("You have read/write permition to use : " + FilePath);
    }
    catch (SecurityException e) 
    {
      return ("You don't have read/write permition to use : " + FilePath);
    }
}

When I call either with correct path or incorrect path the method it always returns message from cathc. 当我使用正确的路径或错误的路径调用该方法时,它将始终从cathc返回消息。

I know its duplicate question I have already gone through many links but no luck !! 我知道它有重复的问题,我已经经历了很多链接,但是没有运气!

Similar Question 类似问题

Similar Question 1 类似问题1

Example : 范例:

PreChecks.PermissionCheck("C:/TEST/G2");
PreChecks.PermissionCheck("C:/Program Files/SAP");

Both calls return the message from catch block where I have all permission on "C:/TEST/G2" and no write permission on "C:/Program Files/SAP". 这两个调用都从catch块返回消息,其中我对“ C:/ TEST / G2”具有所有权限,而对“ C:/ Program Files / SAP”没有写权限。

I have also tried canWrite but it says I have write permissions to "C:/Program Files/SAP" but I know I don't have those. 我也尝试过canWrite,但是它说我对“ C:/ Program Files / SAP”具有写权限,但是我知道我没有这些权限。

The class java.io.File is limited in its capabilities. java.io.File功能受到限制。 Eg 例如

File f=new File("C:\\Program Files\\Java");
System.out.println(f.canWrite());

prints true on my machine though a user process is not allowed to write at this location. 尽管不允许用户进程在此位置写入,但在我的机器上显示true

In contrast, 相反,

Path p=Paths.get("C:\\Program Files\\Java");
System.out.println(Files.isWritable(p));

correctly prints false . 正确打印false

So the solution is to use the NIO API. 因此解决方案是使用NIO API。


The method AccessController.checkPermission has an entirely different purpose. AccessController.checkPermission方法的用途完全不同。 It helps implementing security managers. 它有助于实施安全管理器。 It throws a SecurityException because you don't have an explicitly granted permission to access that directory, but as long as you don't have a SecurityManager installed, that is irrelevant. 它引发SecurityException因为您没有显式授予的访问该目录的权限,但是只要您没有安装SecurityManager ,这都是不相关的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM