1

I am trying to check if a folder is readable in Java 1.6 with the following two manner:

1) Using canRead method of File class. But it's readable all the time (canRead() return always true):

final File folder = new File("file.xml");
if(folder.canRead()){
   // The file is readable
}else{

  // The file is not readable!!
}

2) Using FilePermission class and catch exception. But it catchs the exception all the time (when the folder is readable or not):

try {

  FilePermission filePermission = new FilePermission(folder.getAbsolutePath(), "read");
AccessController.checkPermission(filePermission);

// The file is readable


} catch (AccessControlException pACE) {
 // The file is not readable !!
} 

I have found that there is an issue between Microsoft Windows OS and Java 1.6 for this case.

Bug: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=6203387

Have you any solution?

Walid Ammou
  • 390
  • 1
  • 6
  • 21

2 Answers2

1

What I would do is simply go ahead with a write to that folder. If it works, then all is great, and if not, you can catch the exception.

This is philosophically a Pythonic approach

"It's better to ask for forgiveness than to ask for permission"

but you don't seem to have a choice here.

Here's a good StackOverflow post on exactly this Philosophy: https://stackoverflow.com/questions/6092992/why-is-it-easier-to-ask-forgiveness-than-permission-in-python-but-not-in-java (See 'Update #3' in the question which is a really good example, and somewhat relates to your problem)

Community
  • 1
  • 1
Martin Konecny
  • 57,827
  • 19
  • 139
  • 159
1

This is quick and dirty,

File dir = new File("foo");
if (dir.exists()) {
   if (dir.listFiles() == null) {
      // directory not readable
   }
}

all the IO errors are handled inside of listFiles().

MemLeak
  • 4,456
  • 4
  • 45
  • 84
Steeve McCauley
  • 683
  • 5
  • 11