Home > Mobile >  Reading CSV file into 2D array in Java
Reading CSV file into 2D array in Java

Time:07-14

I have a CSV file that looks like: enter image description here

and I have read this into an ArrayList and would like to index through the ArrayList and print the value (these values vary in types, eg. Strings, doubles and ints). The code i have tried is:

public static void main(String[] args) throws IOException
 
{
    System.out.println("Data from CSV file to be analysed:" "\n");
    String file = "jrc-covid-19-all-days-of-world_ASSIGNMENT-FIXED.csv";
    ArrayList<Integer> lines = new ArrayList<Integer>();
    String line = null;
    try(BufferedReader bufferedReader = new BufferedReader(new FileReader(file)))
    {
        int i = 0;
        while(((line = bufferedReader.readLine()) != null) && i<27)
        {
            String[] values = line.split(",");
            i  ;
            System.out.println(Arrays.toString(values));
        }
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }
    int thirdCountry[] = lines.get(3);
    int cp3 = thirdCountry[6];
    System.out.println(cp3); //should return the value 107122

But I got the error message: incompatible types: Integer cannot be converted to int[].

CodePudding user response:

Since the data in the array can be String or Integer or Double, I declared it as String. I've added some bug fixes towards the end. For doing math, you can use try-catch and the logic I mentioned in the comments.

public static void main(String[] args) throws IOException {
    System.out.println("Data from CSV file to be analysed:" "\n");
    String file = "jrc-covid-19-all-days-of-world_ASSIGNMENT-FIXED.csv";
    ArrayList<String[]> lines = new ArrayList<String[]>();
    String line = null;

    try(BufferedReader bufferedReader = new BufferedReader(new FileReader(file))) {
        int i = 0;
        while(((line = bufferedReader.readLine()) != null) && i<27) {
            lines.add(line.split(","));
            System.out.println(Arrays.toString(lines.get(i)));
            i  ;
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }

    if(lines.size() > 3) {
        String thirdCountry[] = lines.get(3);
            
        if(thirdCountry.length > 6) {
            String cp3 = thirdCountry[6];
            System.out.println(cp3);
        }
    }

}
  • Related