java - 如何在 Java 8 中使用 CSV 值作为构造函数参数

标签 java list csv io java.util.scanner

我正在读取 CSV 文件,并使用文件中的值为文件中的每一行创建一个对象。但是,我收到错误“InputMismatchException”,我发现发生这种情况是因为编译器需要一个字符串,因为 CSV 中的值没有用空格分隔(逗号被作为行的一部分读取)。

但是扫描仪没有替换方法来创建任何空格,所以我假设我必须将文件中的行转换为字符串是否正确?这似乎是将行拆分为值的唯一其他方法。尽管所有值都是字符串,因此它们不适合需要整数/ double 的构造函数参数。如果其中任何内容令人困惑,请告诉我,因为我发现很难解释我遇到的问题。

这是我的代码:

package code;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;

public class Element {
    public int number;
    public String symbol;
    public String name;
    public int group;
    public int period;
    public double weight;

    public Element(int number, String symbol, String name, int group, int period, double weight){

        this.number = number;
        this.symbol = symbol;
        this.name = name;
        this.group = group;
        this.period = period;
        this.weight = weight;
    }

    public String toString(){
        return number + ", " + symbol + ", " + name + ", " + group + ", " + period + ", " + weight;
    }
    public static List<Element> readElements() throws FileNotFoundException{
        Scanner reader = new Scanner(new File("C:\\Users\\Sean\\Desktop\\elements.csv"));
        List<Element> list= new ArrayList<Element>();
        reader.nextLine();

        while (reader.hasNextLine()){
            Element e = new Element(reader.nextInt(), reader.next(), reader.next(), reader.nextInt(), reader.nextInt(), reader.nextDouble());
            list.add(e);
        }
        return list;
    }
}

CSV 文件

Atomic Number,Symbol,Name,Group,Period,Atomic Weight
23,V,Vanadium,5,4,50.9415
54,Xe,Xenon,18,5,131.293
70,Yb,Ytterbium,3,6,173.045

所以我尝试从 CSV 文件中获取值,例如“23”将是第一个 int,并使用它在 while 循环中使用scanner.nextInt 创建一个对象。

最佳答案

您可以使用useDelimiter方法如下:

Scanner reader = new Scanner(new File("C:\\Users\\Sean\\Desktop\\elements.csv"))
                      .useDelimiter(",");

或者,您也可以像这样读取数据:

try (Scanner reader = new Scanner(new File("C:\\Users\\Sean\\Desktop\\elements.csv"))) {
        reader.nextLine();
        while (reader.hasNextLine()){
                String[] tempArray = reader.nextLine().split(",");
                Element e = new Element(Integer.parseInt(tempArray[0]), 
                                        tempArray[1], 
                                        tempArray[2],
                                        Integer.parseInt(tempArray[3]),
                                        Integer.parseInt(tempArray[4]),
                                        Double.parseDouble(tempArray[5]));
                list.add(e);
        }

} catch (IOException e) {
       e.printStackTrace();
}

或者如果您喜欢 Java-8 流,那么另一个解决方案可能是:

List<Element> list = new ArrayList<>();
try (Stream<String> stream = Files.lines(Paths.get("C:\\Users\\Sean\\Desktop\\elements.csv"))) {

     list = stream.skip(1)
                  .map(line -> {
                      String[] tempArray = line.split(",");
                      Element e = new Element(Integer.parseInt(tempArray[0]),
                              tempArray[1],
                              tempArray[2],
                              Integer.parseInt(tempArray[3]),
                              Integer.parseInt(tempArray[4]),
                              Double.parseDouble(tempArray[5]));
                      return e;
                    }).collect(Collectors.toCollection(ArrayList::new));

} catch (IOException e) {
    e.printStackTrace();
}

关于java - 如何在 Java 8 中使用 CSV 值作为构造函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49603130/

相关文章:

java - JPanel 创建两次

java - 通用类型的可比实现?

c# - 是否有一种类型同时包含 : List<T> and also HashSet<T>?

database - 将 `tsv` 文件插入 postgresql 数据库

java - 如何在 Java 中将对象转换为 JTable

java - CriteriaBuilder JPA 2.0 Eclipse链接

java - 为什么部署到GAE的java应用程序不更新cron.xml?

Python 字典键顺序与推导式

c++ - 在 C++ 中使用字符串数组

csv - 如何从 aws 控制台将 dynamoDB 表的整个记录​​导出到 CSV?