简体   繁体   中英

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. Type. (list->Array) Depending on the token we add to one list or another.

Update: The format of the file is fixed. This is the format:

Andrew,Nick,11,Pen,Apple,Backpack,5500.0,570.0,4700.0

Ex:

Name,Description,55.0,100.0

Name into an ArrayList of String.

55.0 into an ArrayList of Double;

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();
}

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