Q:

Check if directory can be opened and list its files

I'm developing a shell in Java. This shell can execute the command find 'regex'. This command finds all the files which have a name that matches the regex, recursively. The method that finds the files is:
 public void findFile(String regExp, String dirName) {
    File dir = new File(dirName);

    if (dir.canRead() == false)
        return;

    File[] files = dir.listFiles();

    for (File file : files) {
        if (file.isFile() == true)
            if (file.getName().matches(regExp) == true)
                System.out.println(file.getAbsolutePath());
        if (file.isDirectory() == true && file.canRead() == true) {
            findFile(regExp, file.getAbsolutePath());
        }
    }
}

But this command fails if directory cannot be opened. For example, in D: partition, I have a hidden directory named found.00 (this directory might belong to the system) and I cannot open this directory. When the method encounters this directory, it fails. How can I check if directory belongs to the system and cannot be opened?

A:

As you use file.canRead() already I would say you could surround the complete content of method findFile(String regExp, String dirName) with a try-catch. You can then catch and log or also ignore the access error. Try the following one please.
public void findFile(final String regExp, final String dirName) {
   try {
      final File dir = new File(dirName);

      if (dir.canRead() == false) {
         return;
      }

      final File[] files = dir.listFiles();

      for (final File file : files) {
         if (file.isFile() && file.getName().matches(regExp)) {
               System.out.println(file.getAbsolutePath());
         }
         if ((file.isDirectory()) && (file.canRead())) {
            findFile(regExp, file.getAbsolutePath());
         }
      }
   } catch (final IOException ignore) {
      System.out.println("No access to '"+dirName+"'.");
   }
}

