file.exist() and broken symlinks

Today I’ve found a problem with file.exists() for broken symlinks on OS X. Here is a simplified code example:

for (File file: files) {
  if (!file.exists()) {
    continue;
  }

  if (file.isDirectory()) {
    deleteRecursively(file);
  }
  else {
    file.delete();
  }
}

This looks quiet fine at the first sight, but this may cause problems if the file is a broken symlink, because file.exists() returns false for a broken symlink. Hence, in the above example code, the broken symlink will not be deleted.

Author: Thomas Singer

Thomas is one of the two CEOs of syntevo. He is a passionated Java developer and likes to design clean and consistent user interfaces.