I would like a code snippet that checks whether a directory has read/write permissions and do something if it does, and does something else if it doesnt. I tried an example shown here:
try {
AccessController.checkPermission(new FilePermission("/tmp/*", "read,write"));
System.out.println("Good");
// Has permission
} catch (SecurityException e) {
// Does not have permission
System.out.println("Bad");
}
The problem is the exception is always triggered, so it always ends up printing "Bad" regardless of whether the directory has write permissions or not. (I chmod the directories to 777 or 000 to test).
Is there an alternative or some way to accomplish what I need?
解决方案
if you just want to check if you can write:
File f = new File("path");
if(f.canWrite()) {
// write access
} else {
// no write access
}
for checking read access, there is a function canRead()