Java扫描仪分隔符错误csv java行尾

标签 java csv delimiter inputmismatchexception

我在扫描 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

输出:

Using file:
/Users/andrewkeithly/netbeansprojects/Trades Exercise/input.csv

51300051409,fbc,273,297
timeStamp: 51300051409
symbol: fbc
quantity: 273
Encountered Error reading file:
java.util.InputMismatchException

最佳答案

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

关于Java扫描仪分隔符错误csv java行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33289751/

相关文章:

java - 使用 Processing 在 Android 中保存现有的 CSV 文件

java - 如何在 Java 中使用 CSV Reader API 返回数据类型

python - 如何使用 Pandas 操作 .csv 文件中的数据并访问特定的行和列?

Java 使用分隔符分割字符串 IndexOutOfBoundException

java - 更改云端点根 URL 似乎不起作用

java - 如何在Java中创建某种对象类型的List?

java - 客户端请求的协议(protocol) SSLv3 未启用或不受支持 (IBM JDK 6.0SR10)

java - 在 fragment 之间导航时保​​存状态

python - 使用两个分隔符将 CSV 导入 pandas

ruby - 在 Ruby 中为 .split 方法使用多个分隔符