Home > Net >  Loading CSV files into an ArrayList
Loading CSV files into an ArrayList

Time:12-05

I have to load data from different CSV files. At the moment, I have this. It works well, but basically I have to load the data from different files into different arrays (one is Books, the other one is customers account). I don't want to repeat the code. I want to make this code (LoadingData) reusable for every CSV file I have to upload. Any ideas on how I can work this out. Here is how my class "Loading" looks so far.

public class LoadingData {

    ArrayList<Book> books = new ArrayList<>();

    //ArrayList<Reader> readers = new ArrayList<>();
    
    public void Loading(String fileName){
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))){
        
            
            String currentLine;
            while ((currentLine = br.readLine()) != null){
                
                // separating the data by the comma
                String[] detailed = currentLine.split(",");

                // skiping the first line since it has only titles and no the data I want to store
                if(detailed[0].equals("id"))
                    continue;
                
                //Storing data in variables

                String id = detailed[0];
                String title = detailed[3];
                String firstName = detailed[1];
                String lastName = detailed [2];
                String genre = detailed [4];  
                
                //adding the data to the arraylist

                books.add(new Book(id, title, firstName, lastName, genre));
               
            }
            
        } catch (IOException ioe) {
            
            ioe.printStackTrace();
        

    }}
}

CodePudding user response:

public class LoadingData {

        public LoadingData(ArrayList<Book> books, String fileName){
            this.file = file;
            this.books = books;
        }


        public ArrayList<Book> Loading(this.fileName){
            try (BufferedReader br = new BufferedReader(new FileReader(fileName))){


                String currentLine;
                while ((currentLine = br.readLine()) != null){

                    // separating the data by the comma
                    String[] detailed = currentLine.split(",");

                    // skiping the first line since it has only titles and no the data I want to store
                    if(detailed[0].equals("id"))
                        continue;

                    //Storing data in variables

                    String id = detailed[0];
                    String title = detailed[3];
                    String firstName = detailed[1];
                    String lastName = detailed [2];
                    String genre = detailed [4];

                    //adding the data to the arraylist

                    books.add(new Book(id, title, firstName, lastName, genre));

                }

            } catch (IOException ioe) {

                ioe.printStackTrace();
            }
            return books;
        }
    }

CodePudding user response:

I understand that you want a single loading method that can handle any CSV file that contains an unknown number of fields in each line of the file.

The below code uses reflection to create objects and adds them to a generic List.

For demonstration purposes, I wrote a minimal implementation of class Book and a sample CSV file which I named books.csv.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class LoadingData {
    List<Object> list = new ArrayList<>();

    public void loading(String fileName, Class<?> theClass) {
        Constructor<?>[] ctors = theClass.getConstructors();
        Constructor<?> ctor = ctors[0];
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String currentLine;
            boolean first = true;
            while ((currentLine = br.readLine()) != null){
                String[] detailed = currentLine.split(",");
                if (first) {
                    first = false;
                    continue;
                }
                Object instance = ctor.newInstance((Object[]) detailed);
                list.add(instance);
            }
        }
        catch (IllegalAccessException    |
               IllegalArgumentException  |
               InstantiationException    |
               InvocationTargetException |
               IOException ioe) {
            ioe.printStackTrace();
        }
    }

    public static void main(String[] args) {
        LoadingData ld = new LoadingData();
        ld.loading("books.csv", Book.class);
        System.out.println(ld.list);
    }
}

class Book {
    String id;
    String title;
    String firstName;
    String lastName;
    String genre;

    public Book(String id, String title, String firstName, String lastName, String genre) {
        this.id = id;
        this.title = title;
        this.firstName = firstName;
        this.lastName = lastName;
        this.genre = genre;
    }

    public String toString() {
        return String.format("%s by %s %s (%s)", title, firstName, lastName, genre);
    }
}

Here is the contents of file books.csv

ID,TITLE,FIRST NAME,LAST NAME,GENRE
1,Moby Dick,Herman,Melville,Adventure
2,To Kill a Mockingbird,Harper,Lee,Fiction

Here is the output when running the above code.

[Moby Dick by Herman Melville (Adventure), To Kill a Mockingbird by Harper Lee (Fiction)]
  • Related