user8010 user8010 -4 years ago 184
Java Question

Convert .csv into a list of arrays

I am reading in a csv file that contains a transport route.
I have the file displaying in the terminal window.

I would like to create a new array for each journey.

The first row of the file is the stop name,then each row after that contains the registration of the vechicle,the time at which the journey starts at stop 1 and the time to get to the next stop(s).

So a journey would consist of the vehicle registration,the stop name and the time when the vehicle should be there.


Stop "Stop1" "Stop2" "Stop3"
R101 650 4 7
R101 710 4 6
R101 730 4 9

Answer Source

If you don't want to use a library you can create a utility method that will convert a CSV into a list of arrays like so;

public static List<String[]> csvToListOfArrays(String file) throws IOException {
   BufferedReader reader = new BufferedReader(new FileReader(file)); 
   List<String[]> arrays = new ArrayList<String[]>(); 
   String line; 
   while ((line = reader.readLine()) != null) {
        String[] tokens = line.split(",");
   return arrays;

In the code above, we create a buffered reader and use the readLine() method to get each line of the CSV one at a time. Then, when we have that line, we call split(",") to split the line into an array of strings on the commas. Lastly, we add the arrays to a list for use later.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download