简体   繁体   中英

Read txt file and print after split action is not printing array value

I am trying to read txt file and then store splitted value in then array, and print all txt file value. But it is not printing the values.

This is how txt file value display as below:

"1675683811","590483002"
"2002199221","876015525"

Following are my code:

String st;
BufferedReader Br = null;
File objFile = new File("C:\\DATA\\File.txt");
Br = new BufferedReader(new FileReader(objFile));
while ((st = Br.readLine()) != null) {
    String value = st.replace("\"", "");
    String[] arraylist = StringUtils.split(value, ",");                     
    for (int i = 0; i <= 1; i++) {
        System.out.println(arraylist[i]);
    }
}                   
Br.close();

Maybe try to write code like below. I changed declaration of split and also way of showing values, because your way could make exception at objects arraylist:

    String st;
    BufferedReader Br = null;
    File objFile = new File("C:\\data\\file.txt");
    Br = new BufferedReader(new FileReader(objFile));
    while ((st = Br.readLine()) != null) {
        String value = st.replace("\"", "");
        String[] arraylist = value.split(",");                     
        for (String row : arraylist) {
            System.out.println(row);
        }
    }                   
    Br.close();

A small change to your code, you can just use String.split method and your for loop will always throws ArrayOutOfBound exception

String st;
    BufferedReader Br = null;
    File objFile = new File("/Users/a602782/input.txt");
    Br = new BufferedReader(new FileReader(objFile));
    while ((st = Br.readLine()) != null) {
        String value = st.replace("\"", "");
        String[] arraylist = value.split(",");                    
        for (int i = 0; i <arraylist.length; i++) {
            System.out.println(arraylist[i]);
        }
    }                   
    Br.close();

And if you want to print each digit on each line you can loop it again inside of for loop

String st;
    BufferedReader Br = null;
    File objFile = new File("/Users/a602782/input.txt");
    Br = new BufferedReader(new FileReader(objFile));
    while ((st = Br.readLine()) != null) {
        String value = st.replace("\"", "");
        String[] arraylist = value.split(",");                    
        for (int i = 0; i <arraylist.length; i++) {
            System.out.println(arraylist[i]);
            for (char c:arraylist[i].toCharArray()) {
                System.out.println(c);
            }
        }
    }                   
    Br.close();

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