Search code examples
javacsvarraylistsequential

How do I print my CSV file to an ArrayList?


Here is my code

package sequentialFilePractice;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ReadFile{

static String line = "";

ReadFile() throws FileNotFoundException{
    readTheFile();
    CSVtoArrayList();
}

public String readTheFile() throws FileNotFoundException{
    String csvFile = "H:\\S6\\AH Computing\\Java Practice\\test.csv";
    BufferedReader br = null;
    String cvsSplitBy = ",";

    try {

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


        }

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


}

public static ArrayList<String> CSVtoArrayList() {
    ArrayList<String> splitCSV = new ArrayList<>();

    if (line != null) {
        String[] splitData = line.split("\\s*,\\s*");
        for (int i = 0; i < splitData.length; i++) {
            if (!(splitData[i] == null) || !(splitData[i].length() == 0)) {
                splitCSV.add(splitData[i].trim());
            }
        }
    }

    for(int j = 0;j < splitCSV.size();j++){
        System.out.println(splitCSV.get(j));
    }
        return splitCSV;
    }

public static void main(String[]args) throws IOException{
    ReadFile f = new ReadFile();
}
}

The code compiles and the file exists. I can print line and it prints the contents of the file however when I print the arrayList, nothing is output so it has not been copied. This is my first use of sequential files in java.


Solution

  • Do you HAVE to read the file manually? If not, you should check out http://opencsv.sourceforge.net/, it allows you to read a CSV directly into a List<String[]> instead of having to deal with the admin of looping, splitting the line and creating a list.

    In essence reducing your code to:

    CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
    List myEntries = reader.readAll();