Java使用split()按.切分出错解决方法

来源:互联网 发布:协方差矩阵的特征值 编辑:程序博客网 时间:2024/06/11 08:00

Java使用split(“.”)出错抛出ArrayIndexOutOfBoundsException


使用情景:

今天在项目中使用split截取图片时抛出了一个截取代码后如下:

@Testpublic void testSpit() {    String s[] = "boy.jpg".split(".");    for (int i = 0; i <= s.length; i++) {        System.out.println(s[i]);    }}

执行上段代码抛出以下异常:

    java.lang.ArrayIndexOutOfBoundsException: 0    at Junit5.testSpit(Junit5.java:92)    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)    at java.lang.reflect.Method.invoke(Method.java:497)    at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:289)

解决办法:








然后我去查api才发现,split()方法接受的是正则表达式,所以传入的”.”就变成了正则表达式的关键字,表示除换行符之外的任意字符。所以,这里需要转义”\.”或”[.]”

@Testpublic void testSpit() {    String s[] = "boy.jpg".split("\\.");    for (int i = 0; i <s.length; i++) {        System.out.println(s[i]);    }}

搞定!

更新时间:2017/9/2 23:03:19

原创粉丝点击