java - 解析包含单行和多行数据的文件

标签 java parsing file-io

我有一个文本文件转储,需要将其转换为分隔文件。该文件包含一系列“记录”(由于缺乏更好的词),格式如下:

User: abc123 
Date: 7/3/12
Subject: the foo is bar
Project: 123456
Problem: foo bar in multiple lines of text
Resolution: foo un-barred in multiple lines of text

User: abc123 
Date: 7/3/12
Subject: the foo is bar
Project: 234567
Problem: foo bar in multiple lines of text
          which may include <newline> and 
          extend to multiple lines of text
Resolution: foo un-barred in multiple lines of text

...

现在,使用 Java,我使用 StringBuffer 逐行读取该文件,根据一系列 if(inputLine.toLowerCase().startsWith("user :")) 将最终分隔行输出到文本文件的逻辑。

但是,字段ProblemResolution 是自由格式,并且可以是多行的。我正在尝试做一些创建两个字符串的事情:附加 Problem: 之后并以 Resolution: 结尾的所有行,并附加 Resolution:< 之后开始的所有行 并以 Form: 结尾。

我已经查看了 this linkthis link ,这表明 StringBuilder 可能是执行此操作的合适方法...但是,我不太确定如何构建逻辑。

编辑: 由于我正在逐行阅读,因此我很难理解如何编码

<pseudocode>
If the line starts with "Problem" extract the charactes after "Problem" else
if the PRIOR line starts with "problem" and the current line doesnt start with "resolution" then append characters in line to prior line
etc.
</pseudocode>

但是,如果有第三行“问题...?我只是无法想象如何使其工作。

有什么想法或替代方法可以实现我想要的结果吗?

最佳答案

您好,如果我正确理解您的问题,那么以下内容应该有效:

    StringBuilder problemDesc = new String....;
    if(inputLine.toLowerCase().startsWith("problem:")){
       problemDesc.append(inputLine);
       while(!inputLine.toLowerCase().startsWith("resolution:"){
           //read next line into inputline;
           problemDesc.append(inputline);
       }
       //deal with problem description here and inputLine now has the line with
       //Resolution in it Repeat same logic for retrieving the resolution value
    }

关于java - 解析包含单行和多行数据的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11311452/

相关文章:

java - 对子类实例使用父类(super class)类型

java - 什么是匹配特定索引处字符的正则表达式?

java - 是否可以让 Play Framework 1 处理 post 请求中发送的 JSON?

c - 编码文本和文件写入读取错误

c++ - fopen 与 ofstream

c++ - 将证书和 png 加载到 char*

java - Java 公共(public)抽象类中方法的默认访问级别是什么?

java - 构造函数内的 ByteBuffer.allocate

c++ - 优化弹性字符串文字解析

javascript - Atom 文本编辑器如何解析/标记代码? (语法高亮)