Here you are catching an exception:
} catch (Exception e) {
fileName = file.getName();
}
While you did a good job knowing to catch an exception, you are being very general; you are just capturing Exception
and tells the person who is reading your code absolutely nothing.
Rather than just catching the generic Exception
, you should be more specific and catch the exception that will be coming out of that line.
I think the exception coming out of this would be from passing -1
to String.substring
, which would happen in there was no last index of "."
.
After reading the documentation, I discovered that the exception that would be raised from this line is the IndexOutOfBoundsException
.
Now, rather than catching the generic Exception
, you should catch IndexOutOfBoundsException
.
A simpler, maybe faster way of getting the string before the "."
would be to just split
the String by the "."
. Then, you'd be left with an array containing the String before the "."
.
Now, getting the name would be this:
fileName = file.getName().split("\\.", 2)[0];
Note: I passed a 2
as a second parameter to split
because this limits how many times the string will be split up. By passing a 2
, this limits to the string only being split a single time, which might speed up performance.
Note two: since split
is looking for a regexular expression and .
is a valid token, I inserted an escape character.