Andrew Maddison

Flowerchild.

Java Diagnose File Not Found Exceptions

Having trouble figuring out those pesky file not found exceptions? Usually it’s some relative path to a test resource file from a mystery working directory somewhere on a test slave (or in my case, a completely sensible path on my local machine that I’d mis-read). Well, the answer is so obvious I’m forcing myself to write it down as pennance for not thinking of it years ago.

1
2
3
4
5
6
7
8
FileInputStream inputStream;
try {
    inputStream = new FileInputStream(someFile);
} catch (FileNotFoundException exception){
    System.out.println(someFile.getAbsolutePath());
    //Logging to debug or trace here would be more sensible, especially in live code.
    throw exception;
}

If the file isn’t found the full path is barfed out so you can figure out where you’re going wrong. No more randomly adding “../” into paths. I really wish something like this happened out of the box, but I guess you’d be leaking a lot of internal system info by default.

Comments