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?
The java. io. FileOutputStream implies(Permission p) method tests if this FilePermission object "implies" the specified permission.
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.
Similarly, we can use Java NIO to check if a File has read permission, write permission, and/or execute permissions.
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.
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 ...)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With