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?
The isReadable() method − This method accepts an object of the Path class and verifies whether the file represented by the given path exists in the system and JVM has permission to read it. If so, it returns true else it returns false.
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.
The java. io. FileOutputStream implies(Permission p) method tests if this FilePermission object "implies" the specified permission.
In Java 7 i do it like this:
if(Files.isWritable(path)){ //ok, write }
Docs
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()
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