简体   繁体   中英

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?

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.

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 \\\\ .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM