简体   繁体   中英

Why am I not being able to split a String in java given that I have a string containing filename?

Basically there are some images in my folder called Patterns. All images are in png file format.

Below is the code I'm using:

import java.io.File;

public class IMG_List {
    public static void main(String [] args){
        File file = new File("C:/images/Patterns");
        String[] str = file.list();
        for(String f_name : str){
            String[] str_name = f_name.split(".");
            System.out.println(str_name[0]);
        }
    }
}

When i use the above code I get:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
    at IMG_List.main(IMG_List.java:11)

However when i use the following code i get no error

import java.io.File;

public class IMG_List {
    public static void main(String [] args){
        File file = new File("C:/images/Patterns");
        String[] str = file.list();
        for(String f_name : str){
            String[] str_name = f_name.split("png");
            System.out.println(str_name[0]);
        }
    }
}

Why am I not being to split the string with the dot ?

Thank you, MMK.

The '.' character in regular expressions means any character, according to the Pattern javadocs .

. Any character (may or may not match line terminators)

So, you get a bunch of empty strings in between the characters. But the no-arg split method discards trailing empty strings, and they're all empty, so you get a 0-length array, which explains the exception you received.

You must escape the '.' character with a backslash. To create a backslash character, you must escape the backslash itself for Java. Try

String[] str_name = f_name.split("\\.");

Then you'll get 2 elements in your array, eg "C:/images/Patterns/example" and "png" .

you have to use escape characters before dot in order to be re-presentable as a regexp since split function accept regexp

public String[] split(String regex)

use \\\\. in regexp to represent dot because . means any character in regexp

您必须逃脱圆点:

String[] str_name = f_name.split("\\.");

如果所有图像均为PNG格式,则也可以使用String.substring()

String st_name = f_name.substring(0,f_name.length()-4);

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