I have to take an input file, and append a number at the end to its name to use as output file. To achieve this, I use the following code:
String delimiter = ".";
String[] splitInput = inputLocation.split(delimiter);
String outputLocation = splitInput[0];
and I get the following exception:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
I added the following statement to check the length of the splitInput array, and I get 0 as output.
System.out.println(splitInput.length);
Later, I used ".x" as delimiter (my file being .xls). I can use ".x" and achieve my purpose but I'm curious why won't "." work?
The split
function uses regular expressions, you have to escape your "." with a "\"
When using regular expressions a "." means any character. Try this
String delimiter = "\\.x";
It should also be mentioned that \
in java is also a special character used to create other special characters. Therefore you have to escape your \
with another \
hence the "\\.x"
Theres some great documentation in the Java docs about all the special characters and what they do:
Java 8 Docs
Java 7 Docs
Java 6 Docs
The .
has a special meaning: Any character (may or may not match line terminators). You can escape it prepending \
or use:
[.]x
e.g.:
String delimiter = "[.]x";
See more in http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With