I have this code that lists all the files in a dir:
File d = getRootDir(cId);
return d.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(FILE_EXTENSION);
}
}
It hangs because, the dir got corrupted and has a file name with invalid chars. Is there an alternate way to do this, so that i can get the list of files and not hang?
Thanks.
Personally whenever I do file operations I will use apache Commons-io. I find the API much easier to work with than Java’s own while still using standard File object.
That said I do not know if switching will make it list without hanging.
Insert a logging statement in your accept method. I’d recommend a logging library but a simple
System.out.println(“Checking ” + name + ” in ” + dir);
Should suffice.
You will now where it is hanging but probably not why. Perhaps it is not hanging for the reason you think it is, the log statement will give you more information on this. You can dig deeper by trace debugging the code though for this you will probably need to download the source code of the JDK.
What is the illegal character you have in your file that is causing problem ?
Also, a second look here at your code. The file name contains the file and extension. By checking with endsWith you risk getting false positive where a file may not have an extention or a different extention. For example :
FILE_EXTENSION = “log”;
The following files will trigger though it will not be what you want.
You can prepend the . before, if you have full control (not user defined configuration) then it will do but a cleaner solution is to extract the extension and compare that. A simple call to FilenameUtils.getExtension will do the trick.