简体   繁体   中英

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.

Example

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

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(",");
        arrays.add(tokens);
   }
   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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM