简体   繁体   English

如何根据文件中的数据类型从CSV文件读取2个ArrayList?

[英]How can I read from a CSV file into 2 ArrayLists depending on the data type I have got in the File?

I'm a beginner in java and I have no clue how to read from a CSV file into 2 ArrayLists maybe using tokens and. 我是Java的初学者,我不知道如何将CSV文件读取到2个ArrayLists中,也许使用标记and。 Type. 类型。 (list->Array) Depending on the token we add to one list or another. (list-> Array)取决于我们添加到一个列表或另一个列表的令牌。

Update: The format of the file is fixed. 更新:文件格式是固定的。 This is the format: 格式如下:

Andrew,Nick,11,Pen,Apple,Backpack,5500.0,570.0,4700.0 安德鲁,尼克,11,笔,苹果,背包,5500.0,570.0,4700.0

Ex: 例如:

Name,Description,55.0,100.0 名称,说明,55.0、100.0

Name into an ArrayList of String. 命名为String的ArrayList。

55.0 into an ArrayList of Double; 55.0放入Double的ArrayList中;

This is my code,im trying to figure out the basic first of all. 这是我的代码,旨在首先弄清基本知识。

public class CSVRead {
    public static void main(String[] arg) throws Exception {

          BufferedReader CSVFile = new BufferedReader(new FileReader("Auto2.csv"));

          String data= CSVFile.readLine(); 

          while (data != null){
           String[] dataArray = data.split(",");
           for (String item:dataArray) { 
              System.out.print(item + "\t"); 
           }
           System.out.println(); 
           data = CSVFile.readLine(); 
          }

          CSVFile.close();


          System.out.println();

         } 
        }

You can try the following code. 您可以尝试以下代码。 As an example I have taken index zero as the name field and the index six as the double value you need. 例如,我将索引零作为名称字段并将索引六作为所需的双精度值。 According to the format you can get the actual field index and add it in to your lists. 根据格式,您可以获取实际的字段索引并将其添加到列表中。

public void loadData() throws IOException {
    List<String> namesList = new ArrayList<>();
    List<Double> someDoubleList = new ArrayList<>();

    BufferedReader CSVFile = new BufferedReader(new FileReader("/Users/leon/Desktop/Auto2.csv"));
    String data = CSVFile.readLine();

    while (data != null) {
        String[] dataArray = data.split(",");
        // Add the names to string list as the index of it is zero
        namesList.add(dataArray[0]);

        // Add the double value to double list as the index of it is six.
        someDoubleList.add(Double.parseDouble(dataArray[6]));
        data = CSVFile.readLine();
    }

    CSVFile.close();
}

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

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