简体   繁体   English

将.csv转换为数组列表

[英]Convert .csv into a list of arrays

I am reading in a csv file that contains a transport route. 我正在读取包含运输路线的csv文件。 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). 文件的第一行是站点名称,其后的每一行都包含车辆的注册信息,旅程从站点1开始的时间以及到达下一个站点的时间。

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; 如果您不想使用库,则可以创建一个实用程序方法,该方法会将CSV转换为数组列表,如下所示:

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. 在上面的代码中,我们创建了一个缓冲的读取器,并使用readLine()方法来一次获取CSV的每一行。 Then, when we have that line, we call split(",") to split the line into an array of strings on the commas. 然后,当我们有该行时,我们调用split(",")将该行拆分为逗号上的字符串数组。 Lastly, we add the arrays to a list for use later. 最后,我们将数组添加到列表中以备后用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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