使用扫描程序从CSV文件读取数据会引发异常

时间:2018-03-22 07:15:21

标签: java csv java.util.scanner

我最近刚开始使用Java,所以请耐心等待。我试图通过读取格式为

的csv文件中的数据来创建对象Product的数组

Name,Price,Stock

但每次我尝试使用Load()函数时,它都会在Product构造函数行中给我一个错误。

  private Product[] product = new Product[100];

  public Product[] Load() throws FileNotFoundException {
    int  counter = 0;
    boolean end = false;

    Scanner scanner = new Scanner(new File("products.csv"));
    scanner.useDelimiter(",");

    while (!end) {
        if (scanner.hasNext()) {
            product[counter] = new Product(scanner.next(), scanner.nextFloat(), scanner.nextInt());
            counter++;
        }
        else {
            end = true;
        }

    }

    scanner.close();
    return product;
}

错误消息为java.util.scanner.next(unknown source) scanner.nextFloat() scanner.nextInt()

的错误相同
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ScoutShop.CSVReader.Load(CSVReader.java:20)
at ScoutShop.Main.main(Main.java:11)

2 个答案:

答案 0 :(得分:0)

生成的java类也应该是products.csv的相同位置。

或者尝试将products.csv放在root或`C:\ products.csv中并执行(看看会发生什么):

 Scanner scanner = new Scanner(new File("C:\\products.csv"));

答案 1 :(得分:0)

检查new File(String path) private Product[] product = new Product[100]; public Product[] load() throws FileNotFoundException { int counter = 0; Scanner scanner = new Scanner(new File("products.csv")); scanner.useDelimiter(","); // try the following while loop without use of if-else statements to // avoid complexity in case of up scaling/maintaining your application while(scanner.hasNext()){ // System.out.print(scanner.next()+"|"); product[counter] = new Product(scanner.next(), scanner.nextFloat(), scanner.nextInt()); counter++; } scanner.close(); return product; } 是否知道您必须指定要尝试阅读的文件的确切文件路径

通过Java Docs

查看CSV解析CSV Parsing errors的答案
...
 rules: [
      {
        test: /\.(js|jsx)$/,
        exclude: /node_modules/,
        use: ["babel-loader"]
      },
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      }
    ]
...