简体   繁体   English

使用java.util.scanner读取和解析文件

[英]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. 我有一个文本文件,我想用java.util.Scanner读取并解析内容。

File look like this: 文件看起来像这样:

Number of objects: 5 物件数量:5
Description 0 Some description 描述0一些描述
:Description 1 Some description :描述1一些描述
: more description of object 1 :对象1的更多描述
: Even more description of object 1 :对象1的更多描述
: more description of object 1 :对象1的更多描述
Description 2 Some description of object 2 描述2对象2的一些描述
: more description of object 2 :对象2的更多描述
Description 3 Some description of object 3 描述3对象3的一些描述
: more description of object 3 :对象3的更多描述
Description 4 Some description of object 4 描述4对象4的一些描述
: more description of object 4 :对象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;
    }
}

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

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