Why does the second line of this code throw ArrayIndexOutOfBoundsException?
String filename = "D:/some folder/001.docx";
String extensionRemoved = filename.split(".")[0];
While this works:
String driveLetter = filename.split("/")[0];
I use Java 7.
You need to escape the dot if you want to split on a literal dot:
Otherwise you are splitting on the regex
., which means “any character”.Note the double backslash needed to create a single backslash in the regex.
You’re getting an
ArrayIndexOutOfBoundsExceptionbecause your input string is just a dot, ie".", which is an edge case that produces an empty array when split on dot;split(regex)removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you’re left with an empty array.To avoid getting an
ArrayIndexOutOfBoundsExceptionfor this edge case, use the overloaded version ofsplit(regex, limit), which has a second parameter that is the size limit for the resulting array. Whenlimitis negative, the behaviour of removing trailing blanks from the resulting array is disabled:ie, when
filenameis just a dot".", callingfilename.split("\\.", -1)[0]will return a blank, but callingfilename.split("\\.")[0]will throw anArrayIndexOutOfBoundsException.