Leem.fin
Leem.fin

Reputation: 42582

ArrayIndexOutOfBoundsException after String.split()

I got a string value from server:

String fileName = requestServer();

//My log shows fileName="properties.txt"

String name = fileName.trim().split(".")[0];

But when I try to get the name without ".txt" with above code, I got

ArrayIndexOutOfBoundsException: length=0, index=0.

I don't see where my code is wrong, why I get this exception?

Upvotes: 1

Views: 243

Answers (3)

Kick
Kick

Reputation: 4923

Use this

String name = fileName.trim().split("\\.")[0];

Explanation of the regex \.

. is a regex metacharacter to match anything (except newline). Since we want to match a literal . we escape it with . Since both Java Strings and regex engine use \ as escape character we need to use \\.

Upvotes: 0

grexter89
grexter89

Reputation: 1102

split(...) returns an empty array, because it takes a regex as argument. "." is for every word character. The characters, that are found by that regex aren't included in the result.

Use "\\." instead to split.

Upvotes: 0

npinti
npinti

Reputation: 52185

This: String name = fileName.trim().split(".")[0]; should be like so: String name = fileName.trim().split("\\.")[0];. The . in regex language means any character (since String.split() takes a regular expression as a parameter.), which causes the string to be split on each character thus returning an empty array.

The \ infront of . will escape the period and cause the regex engine to treat it like an actual . character. The extra \ is needed so that the initial \ can be escaped.

Upvotes: 7

Related Questions