In Java, I am trying to list the files and folders in my C:\ directory and loop through them using:
File[] files = new File("C:\\").listFiles();
However, to my surprise when I loop through the array I find that the first index is C:\Documents and Settings! For a starters, I’m running Windows 7 Home Premium and I haven’t even upgraded from Windows XP or anything but no matter what I do I can not see this folder on my drive, dispite choosing to view hidden folders!?
Furthermore, as you would suspect, when you start to use a recursive method to look through every folder on the drive it throws a NullPointerException as soon as it tries to list the files in that directory.
Does anyone know why this is, or even better how to solve the issue? Any idea’s appreciated, thanks in advance
UPDATE: I’ve now very quickly established that C:\Documents and Settiings is a symlink or “JUNCTION”, so know by question is: how do I determine that it is a symlink in Java so that I can tell the for loop to skip any?
Ok I think this warrants a full answer here. There are several things going on at once here which makes it a bit more interesting than on first glance.
Yes
Documents and Settingsis a symlink under Vista+, no that’s not the problem we have here. The real problem is that the folder has some extremely restricted access rights – by default not even Admins have access to it.If we read the
isSymbolicLinkjavadoc it clearly states:Since we don’t have any rights to access the directory we cannot determine whether it is a symbolic link or not. But since we then try to access the file anyhow we get an exception telling us we can’t access the file.
Hence the correct check should look something like this: