1

Hi I'm having issues with the code below (file is of the File class):

String[] fileNameSplit = file.getName().split(".");
String fileType = fileNameSplit[(fileNameSplit.length - 1)];

It always throws a ArrayOutOfBoundsExecption at -1 suggesting that fileNameSplit is 0. When I take out the -1 it still says ArrayOutOfBoundsException but now at 0, meaning it is empty.

What am I doing wrong?

3 Answers 3

5

This is because . is a meta-character that accepts "any character". It treats every single character of your string as a delimiter, "eating up" its entire content.

Escape the dot it like this:

String[] fileNameSplit = file.getName().split("\\.");

or use a character class, like this:

String[] fileNameSplit = file.getName().split("[.]");
Sign up to request clarification or add additional context in comments.

Comments

1

Use \\.

String[] fileNameSplit = file.getName().split("\\.");

As regex and String don't go well with each other, 1st \ is needed to be used to make the compiler realize that its not a dot(.) but a regex, and 2nd \ to make the java compiler take \ as literally.

2 Comments

Yes sorry you were but I'm using the "[.]" way rather than the "\\." way so I thought I would give credit where it was due... When my rep is high enough I will upvote up though
@AqueousSnake no its perfectly fine.. No need to upvote it any further... but please mention you needs before hand, so you can get the apt answer.... \\. is the most common way of doing it..so i mentioned it... well whats done is done... fine... but thanks for that upvote...
1

Note that the argument to the split method is a regex. In the regex, the dot has a special meaning: match any character.

To use the dot literally, you'll need to escape it:

`String[] fileNameSplit = file.getName().split("\\.");`

docs for the split method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.