java - 如何从 CSV 数据的第二行开始扫描到链接列表?

标签 java linked-list java.util.scanner

所以我的 CSV 文件包含类似于 Excel 中的内容

     speed period warning pair
 1     26     1      1      1
 2     26     1      1      1
 3     26     1      1      1
 4     26     1      1      1

在我的扫描仪文件中,我有

public class scanner {

    public static void main(String[] args) throws IOException {
        // open file input stream
        BufferedReader reader = new BufferedReader(new FileReader(
                "amis.csv"));

        // read file line by line
        String line = null;
        Scanner scanner = null;
        int index = 0;
        List<amis> empList = new ArrayList<>();

        while ((line = reader.readLine()) != null) {
            amis emp = new amis();
            scanner = new Scanner(line);
            scanner.useDelimiter(",");
            while (scanner.hasNext()) {
                String data = scanner.next();
                if (index == 0) {
                    emp.setId(data);
                } else if (index == 4) {
                    emp.setPair(data);
                } else if (index == 3) {
                    emp.setWarning(data);
                } else if (index == 2) {
                    emp.setPeriod(data);
                }else if (index == 1) {
                    emp.setSpeed(data);
                }else {
                    System.out.println("invalid data::" + data);
                }
                index++;
            }
            index = 0;
            empList.add(emp);
        }

        //close reader
        reader.close();

        System.out.println(empList);

    }

但是我的链接列表的输出将显示

ID=""::Pair="pair"::Warning="警告"::Period="period"::Speed="speed",

ID="1"::Pair=1::Warning=1::Period=1::Speed=26,

ID="2"::Pair=1::Warning=1::Period=1::Speed=26,

ID="3"::Pair=1::Warning=1::Period=1::Speed=26,

ID="4"::Pair=1::Warning=1::Period=1::Speed=26,

如何从第二行开始。

最佳答案

您可以在 while 循环之前调用 scanner.nextLine,例如:

String headers = reader.nextLine();
while ((line = reader.readLine()) != null) {

文档是这样说的:

Advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.

因此,在 while 循环中,您将获得第二行中的所有行。

关于java - 如何从 CSV 数据的第二行开始扫描到链接列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42319341/

相关文章:

java - 使用扫描仪输入时如何写出表格?

java - 不能转换为 java.lang.Comparable

java - hql 通过集合查找实体

java - 如何从 Java 中的链表中删除特定值?

java - 使用来自 Java 的扫描仪打印文件中的元素

Java 正则表达式 hasNext() 匹配下一个的结尾

java - 如何在 Eclipse IDE 中将 JSON 关联到字符串

java - JPA自定义JDBC批量大小不起作用

c++ - unique_ptr 链表插入 - 与 operator= 不匹配

c++ - 在 C++ 中取消引用 void 指针