Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check write permissions of a directory in java?

Tags:

java

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?

like image 361
Revelier Avatar asked Jun 03 '11 19:06

Revelier


People also ask

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

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.

How do I check if a folder has write 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.

How do I check permissions in java?

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


2 Answers

In Java 7 i do it like this:

if(Files.isWritable(path)){   //ok, write } 

Docs

like image 139
Robert Niestroj Avatar answered Sep 19 '22 23:09

Robert Niestroj


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()

like image 40
MarioP Avatar answered Sep 16 '22 23:09

MarioP