【问题标题】:Java scanner delimiter error csv java end of lineJava扫描仪分隔符错误csv java行尾
【发布时间】:2015-10-22 20:06:37
【问题描述】:

我在扫描 csv 的最后一个整数时收到 InputMismatchException

public class TradeSim {
    public void readFile(String fileName) {
        try {
            // file name and absolute path
            File file = new File(fileName);
            String fullPath = file.getAbsolutePath();
            System.out.println("Using file:\n" + fullPath + "\n");

            // set File Input Stream to Full Path
            FileInputStream inputStream = new FileInputStream(fullPath);

            // open input stream and retrieve data
            Scanner scanner = new Scanner(inputStream);
            scanner.useDelimiter(System.getProperty("line.separator"));
            while (scanner.hasNext()) {
                String data = scanner.next(); // gets a whole line
                System.out.println(data);
                parseCSVLine(data);
            }
            scanner.close();
        } catch (Exception e) {
            System.out.println("Encountered Error reading file:\n" + e.toString() + "\n");
        }
    }

    public void parseCSVLine(String line) {
        Scanner scanner = new Scanner(line);
        scanner.useDelimiter(",");
        long timeStamp = scanner.nextLong();
        System.out.println("timeStamp: " + timeStamp);
        String symbol = scanner.next();
        System.out.println("symbol: " + symbol);
        int quantity = scanner.nextInt();
        System.out.println("quantity: " + quantity);
        int price = scanner.nextInt(); //Error occurs here!!
        System.out.println("price: " + price);
        Trades trades = new Trades(timeStamp, symbol, quantity, price);
    }
}

文件内容:

51300051409,fbc,273,297
51300073658,cef,250,262

输出:

使用文件:
/Users/andrewkeithly/netbeansprojects/Trades Exercise/input.csv

51300051409,fbc,273,297
时间戳:51300051409
符号:fbc
数量:273
读取文件时遇到错误:
java.util.InputMismatchException

【问题讨论】:

  • 也许它在那个位置不是 int 。首先将整个扫描过程包含在 try catch 块中,最好使用scanner.next()。稍后您可以根据需要进行解析
  • @AbtPst 感谢您的回复!它正在读取的行是: 它扫描前 3 个,无法扫描最后的 int 297。整个扫描过程在调用 parseCSVLine 方法的 try catch 块中。
  • 如果你使用next()会起作用吗?
  • 不,这是我尝试的第一件事。我认为这与行尾分隔符有关。
  • @andrewkeithly 欢迎来到 SO。每当您寻求有关异常的帮助时,在代码示例中发布堆栈跟踪和相应行很有用。

标签: java csv delimiter inputmismatchexception


【解决方案1】:

问题已解决: System.getProperty("line.separator") 正在寻找 csv 未使用的 Unix 特定分隔符。 只需将代码更改为scanner.useDelimiter("\r?\n"); 即可解决我的问题。谢谢@Tom!

【讨论】:

  • 请不要使用useDelimiter(" "),这看起来会造成更多麻烦。请改用useDelimiter("\r?\n")。如果它在那里,它会读取"\r",并且肯定会读取"\n",因此适用于 Unix 和 Windows。
猜你喜欢
  • 2014-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-26
  • 1970-01-01
  • 2011-01-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多