Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check file permissions in Java (OS independently)

I have the following snippet of code:

public class ExampleClass {

public static void main(String[] args) throws FileNotFoundException {
    String filePath = args[0];
    File file = new File(filePath);

    if (!file.exists())
        throw new FileNotFoundException();

    if (file.canWrite())
        System.out.println(file.getAbsolutePath() + ": CAN WRITE!!!");
    else
        System.out.println(file.getAbsolutePath() + ": CANNOT WRITE!!!!!");

    if (file.canRead())
        System.out.println(file.getAbsolutePath() + ": CAN READ!!!");
    else
        System.out.println(file.getAbsolutePath() + ": CANNOT READ!!!!!");

    if (file.canExecute())
        System.out.println(file.getAbsolutePath() + ": CAN EXECUTE!!!");
    else
        System.out.println(file.getAbsolutePath() + ": CANNOT EXECUTE!!!!!");
}
}

It works in Linux OS, but the problem is that it doesn't work in windows7. So the question is: Does anybody know a method to check privileges to a file in Java OS INDEPENDENTLY?

like image 852
Jarosław Drabek Avatar asked May 28 '12 11:05

Jarosław Drabek


People also ask

How do I check permissions in Java?

The java. io. FileOutputStream implies(Permission p) method tests if this FilePermission object "implies" the specified permission.

How do you check the permission of a file or directory in Java?

How to check if File or Directory has Write Permission in Java. boolean canWrite() : this method is used to check that our application can have access to write on the file or not.

Which file permission can you check using Java in IO API?

Similarly, we can use Java NIO to check if a File has read permission, write permission, and/or execute permissions.

How can you check existing permissions of a file?

Step 2 – Right-click the folder or file and click “Properties” in the context menu. Step 3 – Switch to “Security” tab and click “Advanced”. Step 4 – In the “Permissions” tab, you can see the permissions held by users over a particular file or folder.


Video Answer


1 Answers

This might be caused by something (for instance an anti-virus product) "mediating" file access in an inconsistent way.

Certainly, it is hard to believe that the Java File.canXxxx() methods are generally broken on any flavour of Windows.


UPDATE - I take that back. Read this Sun bug report ... and weep. The short answer is that it is a Windows bug, and Sun decided not to work around it. (But the new Java 7 APIs do work ...)

FWIW, I maintain that it is BAD PRACTICE to try to check file access permissions like that. It is better to simply attempt to use the file, and catch the exceptions if / when they occur. See https://stackoverflow.com/a/6093037/139985 for my reasoning. (And now we have another reason ...)

like image 100
Stephen C Avatar answered Oct 01 '22 19:10

Stephen C