简体   繁体   中英

Reading and parsing a file with java.util.scanner

I have a textfile i would like to read with the java.util.Scanner and parse the content.

File look like this:

Number of objects: 5
Description 0 Some description
:Description 1 Some description
: more description of object 1
: Even more description of object 1
: more description of object 1
Description 2 Some description of object 2
: more description of object 2
Description 3 Some description of object 3
: more description of object 3
Description 4 Some description of object 4
: more description of object 4

I've gotten so far has this

  String pattern = "description";
  String pattern2 = ":";
  int romNummer = 0;
  fil = new Scanner(new File(filnavn));
  do{
      String input;
      input = fil.next();
      romNummer = fil.nextInt();
      String description = fil.nextLine();

      if(fil.hasNext(":")){
          input = fil.next();
          String description2 = fil.nextLine();
          description += description2;
      }
      if(fil.hasNext(":")){
          input = fil.next();
          String description2 = fil.nextLine();
          description2 += description2;
      }
      if(fil.hasNext(":")){
          input = fil.next();
          String description2 = fil.nextLine();
          description += description2;
      }

  }while (fil.hasNext(pattern)||fil.hasNext(pattern2));

I want all of description for one object as one string. Is there a more elegant way of doing this with the scanner class?

为什么不阅读每一行,然后确定它是一个新的Description,还是将第一个字符添加到当前Description之后是否是“:”?

Pseudo code

fil = new Scanner(new File(filnavn));
String line = "",result="";
int number=0;
number = Integer.parseInt(fil.nextLine().split(":").[1].trim()); 
while(fil.hasNext())
{ 
    line = fil.nextLine();

    Check if line starts with "Description"
    {
         Print content
         remove "Description [number]" from line
         content += line;
    }
    Check if line starts with ":"
    {
         remove ":"
         content += line;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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