如何从CSV文件中获取数据并将其放在列表中

时间:2018-03-22 15:46:19

标签: java csv

我想用Java中的CSV文件读取数据,然后将这些数据放入列表中。 CSV中的数据放入行中,如下所示: 数据,32,4.3 月,5月2日,5月5日

我目前的代码只打印[32]。

ArrayList<String> myList = new ArrayList<String>();

Scanner scanner = new Scanner(new File("\\C:\\Users\\Book1.csv\\"));
scanner.useDelimiter(",");
while(scanner.hasNext()){
    myList.add(scanner.next());
    for (int i = 0; i <= myList.size(); i++) {
        System.out.println(myList.toString());
    }
    scanner.close();
}

2 个答案:

答案 0 :(得分:3)

也许这段代码可以帮助你,也许这段代码与你的代码不同,你使用arrayList而我使用常规数组。

数据示例:

  • Farhan,3.84,4,72
  • Rajab,2.98,4,72
  • Agil,2.72,4,72
  • Alpin,3.11,4,73
  • Mono,3,6,118 K
  • imel,3.97,7,132
  • Rano,2.12,6,110
  • Kukuh,4,1,22

将逗号分隔的csv文件中的每一行数据放入每个索引的数组中

    int tmp = 0;
    String read;
    Mahasiswa[] mhs = new Mahasiswa[100];

    BufferedWriter outs;
    BufferedReader ins;
    BufferedReader br = new BufferedReader(new 
    InputStreamReader(System.in));
    Scanner input = new Scanner(System.in);

    try {
        ins = new BufferedReader(new FileReader("src/file.csv"));
        tmp = 0;
        while ((read = ins.readLine()) != null) {
            String[] siswa = read.split(",");
            mhs[tmp] = new Mahasiswa();
            mhs[tmp].nama = siswa[0];
            mhs[tmp].ipk = Float.parseFloat(siswa[1]);
            mhs[tmp].sem = Integer.parseInt(siswa[2]);
            mhs[tmp].sks = Integer.parseInt(siswa[3]);
            tmp++;
            i++;
        }
        ins.close();
    } catch (IOException e) {
        System.out.println("Terdapat Masalah: " + e);
    }

打印数组数据

  tmp = 0; 
  while (tmp < i) {
  System.out.println(mhs[tmp].nama + "\t\t" + 
                      mhs[tmp].ipk + "\t\t" + 
                      mhs[tmp].sem + "\t\t" + 
                      mhs[tmp].sks);
                    tmp++;
                }

答案 1 :(得分:0)

ArrayList<String> myList = new ArrayList<String>();
try (Scanner scanner = new Scanner(new File("C:\\Users\\Book1.csv"))) { 
    //here at your code there are backslashes at front and end of the path that was the
    //main reason you are not able to read csv file
            scanner.useDelimiter(",");
            while (scanner.hasNext()) {
                myList.add(scanner.next());
            }
            for (int i = 0; i < myList.size(); i++) { //remember index is always equal to "length - 1"
                System.out.println(myList);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

你也没有处理FileNotFoundException

希望这会有所帮助:)