0

我试图读取一个 CSV 文件,但返回的是一整列值,我如何单独使用每一行(现在已经使用 java 4 天了,所以请善待我的无能:D)

package mypackage;

import java.io.FileReader;
import java.io.IOException;
import au.com.bytecode.opencsv.*;


public class CSVData {

    private static final String FILE_PATH="D:\\eclipse\\250.csv";

    public static void main(String[] args) throws IOException {

        CSVReader reader = new CSVReader(new FileReader(FILE_PATH));
        String [] nextLine;
        while ((nextLine = reader.readNext()) != null) {
            String a = nextLine[2];
            System.out.println(a);
        }

    }
}

输出如下:

性别
女性
男性
男性
女性
女性
女性
男性

我希望能够将每一行用作单独的值,例如 nextLine[2][1] 但它不起作用

4

1 回答 1

0

您必须先阅读整个内容,然后将其分配给列表或数组。假设您的 csv 有五列(我不确定如何动态获取列数),这是我的快速操作:

public static void main(String[] args) throws IOException {

    CSVReader reader = new CSVReader(new FileReader(FILE_PATH));
    ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();
    while ((nextLine = reader.readNext()) != null) {
        ArrayList<String> list = new ArrayList<String>();
        for (int i=0;i<5;i++) { //i<5 is hardcoded; get actual function for number of columns
           list.add(nextLine[i]);
        }
        array.add(list);
    }
    // example for nested loop to display results
    for(x=0;x<array.size();x++) {
        for(y=0;y<array.get(x).size();y++) {
            System.out.print(array.get(x).get(y) + " ");
        }
        System.out.println(" ");
    }
    // example to display specific item
    System.out.println(array.get(1).get(1));
}

我确信有一种更简洁的方法可以做到这一点(保存表数据然后放置在列表中的对象会更好),但你明白了。您可以稍后使用 list.get(x) 或 list.get(x).get(y) 和循环来检索数据。

于 2013-07-09T07:30:19.197 回答