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

时间:2015-10-22 20:06:37

标签: java csv delimiter inputmismatchexception

我在csv的最后一个int中扫描时收到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,273297
  51300073658,CEF,250262

输出:

  

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

     

51300051409,FBC,273297
  timeStamp:51300051409
  符号:fbc
  数量:273
  遇到错误读取文件:
  java.util.InputMismatchException

1 个答案:

答案 0 :(得分:3)

解决问题: <!DOCTYPE html> <html> <head> <title>Data Layer: Simple</title> <meta name="viewport" content="initial-scale=1.0"> <meta charset="utf-8"> <style> html, body { height: 100%; margin: 0; padding: 0; } #map { height: 100%; } </style> </head> <body> <div id="map"></div> <script> var map; function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: {lat: 38.55914, lng: -121.423473}, zoom: 16, disableDefaultUI: true }); // NOTE: This uses cross-domain XHR, and may not work on older browsers. map.data.loadGeoJson('file:///GOOGLE_MAPS_JAVASCIPT/csus_locations.JSON'); } google.maps.event.addDomListener(window, 'load', initialize); </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=&callback=initMap"></script> </body> </html> 正在寻找csv不使用的Unix特定分隔符。 只需将代码更改为System.getProperty("line.separator")即可解决我的问题。谢谢@Tom!

相关问题