简体   繁体   中英

While printing array list only last value is printed

I am trying to read CSV file that has value in only one column like

11111
22222
33333
44444

I am able to read the file but when I am printing the value that only prints the last value, that is 44444. Below is my code, please help me to get all the values in list and print:-

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ReadCVS {

  public static void main(String[] args) {

    ReadCVS obj = new ReadCVS();
    obj.run();

  }

  @SuppressWarnings("unchecked")
public void run() {

    String csvFile = "/C:/Users/SONY/Desktop/Book1.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";
    List<String[]> list=new ArrayList<String[]>();

    try {

        br = new BufferedReader(new FileReader(csvFile));
        String[] country = null ;
        while ((line = br.readLine()) != null) {

            country= line.split(cvsSplitBy);

            list.add(country);
            System.out.println(Arrays.toString(country));
        }

        for(int i = 0; i < country.length; i++) {
            System.out.println(Arrays.toString(country));             
        }


    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    System.out.println("Done");
  }

}

The problem is that you are printing country in the second for loop which contains that value of the last column which in your case is 44444

Try something like this.

List<String[]> list = new ArrayList();
try {
    list.add(new String[]{"a","b"});
    list.add(new String[]{"c","d"});
    
    for (String[] str: list) {
        System.out.println(Arrays.toString(str));
    }
} catch (Exception e) {}    

Output:

[a, b]

[c, d]

It's a generic example trying to simulate yours. Make changes as per your requirements. And never leave exceptions uncaught like I did in my example above.

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