0

I tried to write code to read csv file, and I stored the data in an array of object but after every change in the number of columns, I should read another column and change the code. because I want to use the same class for different csv files with different number of columns without need to change the code for every file.

    public class Read_CSV {
        public static Object[][]readCSVdata(String csvFilePath){
     //String csvFilePath = null;
     ArrayList<Object[]>dataList = new ArrayList <Object[]>();
        String line = "";
          String cvsSplitBy = ",";
        try (BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {

        int iteration = 0;
        
        while ((line = br.readLine()) != null) {
            if(iteration == 0) {
                iteration++;  
                continue;
            }
            String[] arri = line.split(cvsSplitBy);
            Object[]arri1= {arri[0] , arri[1],arri[2] };
              //here after every additional column I should add another cell
            dataList.add(arri1);
        }      
        br.close();
        return dataList.toArray(new Object[dataList.size()][]);

    } catch (IOException e) {
        e.printStackTrace();
        return null;

    }

}

}

1 Answer 1

1

You could use the array of strings after splitting each line:

while ((line = br.readLine()) != null) {
    if(iteration == 0) {
        iteration++;  
        continue;
    }
    String[] arri = line.split(cvsSplitBy);
    
    dataList.add(arri);
} 

Then dataList will contain arrays of strings.

Or you have some other requirements?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.