简体   繁体   English

从文件读取数据时遇到问题-Java

[英]Having problems reading data from a file - java

I'm pretty sure it has something to do with delimiters and I'm relatively new with Java and can't seem to find an answer. 我很确定它与定界符有关,而且我对Java还是比较新的东西,似乎找不到答案。 I have to read from a file called Simulation.Configuration which has this data in it: 我必须读取一个名为Simulation.Configuration的文件,该文件中包含以下数据:

    dimensionX: 100
    dimensionY: 100
    numberOfMobileObjects: 5
    durationOfSimulationTime: 10
    WarningGeotask: 1, 3
    WarningGeotask: 2, 3
    CounterGeotask: 1, 3
    PopuplationMonitoringGeotask: 2, 3, 3

I have a scanner reading through to find the data and do certain things with them. 我有一个扫描仪通读以查找数据并对其进行某些处理。 I can easily get past the labels (dimensionX, dimensionY, and so forth)but can't seem to get to the numbers. 我可以轻松地绕过标签(dimensionX,dimensionY等),但似乎看不到数字。 I've tried a lot of ways using delimiters to reach those numbers, but cannot seem to get to them.The most recent one I've tried is using 我已经尝试了很多使用定界符来达到这些数字的方法,但似乎无法达到它们。我尝试过的最新方法是使用

scanner.useDelimiter("[ ,:]");

to get through to the data. 进入数据。 When I do this, it gives me an InputMismatchException. 当我这样做时,它会给我一个InputMismatchException。 Here's how I am reading the file: 这是我读取文件的方式:

    Scanner scanConfig = new Scanner(new File("Simulation.Configuration"));

    scanConfig.useDelimiter("[ ,:]");

    int dimensionX = 0;
    int dimensionY = 0;
    int numberOfMobileObjects = 0;


    while(scanConfig.hasNextLine()){

        String nextLabel = scanConfig.next();
        if(nextLabel.equals("dimensionX")){

            dimensionX = scanConfig.nextInt();
        }
        if(nextLabel.equals("dimensionY")){

            dimensionY = scanConfig.nextInt();
        }
        if(nextLabel.equals("numberOfMobileObjects")){

            numberOfMobileObjects = scanConfig.nextInt();
        }

I've looked all over and couldn't find anything that helped my situation. 我四处张望,找不到任何有助于我的处境的东西。 Any tips on this would be lovely. 任何提示,这将是可爱的。

The regex you've provided for the delimiter isn't doing what you think it is. 您为定界符提供的正则表达式未按照您认为的那样做。 I would take this approach instead. 我会改用这种方法。

String input = scanner.nextLine();
String[] array = input.split(":");
String label = array[0];
String data = array[1];    
String[] number = data.split(",");   
Integer x = new Integer(number[0]);

Documentation for String#split() String#split()的文档

Your useDelimiter argument is wrong. 您的useDelimiter参数错误。 "[ ,:]" uses exactly one character as a delimiter. “ [,:]”仅使用一个字符作为分隔符。 You want any set of those. 您需要任何一组。 Simply change it to: "[ ,:]+". 只需将其更改为:“ [[,:] +”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM