如何将多行记录从文本文件转换为Stream <list <string>&gt;?

时间:2017-02-03 21:43:25

标签: java java-8 java-stream

我有一个包含以下记录的文本文件:

--------------------
Field1=Value1
Field2=Value2
Field3=Value3
EOR
---------------------
Field1=Value1
Field2=Value2
Field3=Value3
Field4=Value4
Field5=Value5
EOR

每条记录可以有多行。每条记录的结尾都标有&#34; EOR&#34;。

我想将这些行从文本文件处理成记录流,例如Stream<List<Record>>。到目前为止,我只能使用Files.lines(pathToFile)获得Stream<String>形式的文件,其中每个元素都是一行。

我正在寻找一种方法将这个字符串流转换为List<String>的流。

2 个答案:

答案 0 :(得分:4)

使用StreamEx

StreamEx.of(Files.lines(pathToFile))
    .groupRuns((s, s2) -> !"EOR".equals(s))
    .collect(Collectors.toList()));

答案 1 :(得分:3)

假设您不想引入任何依赖项,编写Iterator然后对其进行流式处理非常简单。

public class SampleJava {
public static void main(String args[]) throws IOException {
    try(Stream<String> lines = Files.lines(Paths.get("records.txt"))) {
        new RecordIterator(lines).stream().forEach(System.out::println);
    }
}
static class RecordIterator implements Iterator<List<String>>
{
    private final static String SEP = "---";
    private final static String EOR = "EOR";
    private final Iterator<String> lines;
    public RecordIterator(Stream<String> lines) {
        this.lines = lines.iterator();
    }
    @Override
    public boolean hasNext() {
        return lines.hasNext();
    }
    @Override
    public List<String> next() {
        if(!hasNext()) throw new NoSuchElementException();
        List<String> record = new ArrayList<>();
        do {
            String next = lines.next();
            if(next.startsWith(SEP)) continue;
            if(next.equals(EOR)) break;
            record.add(next);
        } while(hasNext());
        return record;
    }
    public Stream<List<String>> stream() {
        Iterable<List<String>> itor = ()-> this;
        return StreamSupport.stream(itor.spliterator(), false);
    }
}
}

<强>输出:

  

[Field1 = Value1,Field2 = Value2,Field3 = Value3]

     

[Field1 = Value1,Field2 = Value2,Field3 = Value3,Field4 = Value4,Field5 = Value5]

相关问题