5

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?

Purple
  • 104
  • 13
DT7
  • 1,615
  • 14
  • 26
  • 3
    try using "\." instead. I'm not in a place where I can check it, but I think that split expects a regex, and the . character represents any character. – Kylar Sep 06 '13 at 17:48
  • @LuiggiMendoza, thanks. I got my answer there.. – DT7 Sep 06 '13 at 17:50
  • @Kylar, My filename is like c:/temp/sample.xsl.. I needed the c:/temp/sample and add a number like 123 and then add .xls to it. Initially I thought I could just split into two parts around the . , and add the number in middle.. Now I split using ".x" and get the first part, add the number and have the extension hard-coded. Thanks :) – DT7 Sep 06 '13 at 17:51

4 Answers4

12

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

ug_
  • 11,267
  • 2
  • 35
  • 52
2

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

Paul Vargas
  • 41,222
  • 15
  • 102
  • 148
1

. is considered as any character in regex. Please use escape character \ (which also needs to be escaped as \\), if you want to override the special meaning of it.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
1

String.split() expects a regex as input. In Java regexes, . character is a special character. Thus, your split statement is not working the way you expected. You should escape your "." as \\..

Mauren
  • 1,955
  • 2
  • 18
  • 28