How to check file permissions in Java (OS independently)

file-permissions, java

Solution

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

However, 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 ...)

Problem

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?

Original source