如何从java中的文本文件中读取数据,条件是必须从一个位置读取数据到另一个位置

问题描述 投票:1回答:1

我想首先从事件1到结束1读取文本文件,然后从事件2到结束2再读取,依此类推,代码中将有多行代码在一个事件与另一个事件之间。文本文件如下:

event 1 arg  arg  arg  end 1 
event 2 arg arg arg end 2
java buffer text-files
1个回答
0
投票

如果我理解,试试吧

public void method() {
    String file = "C:\\text.txt";
    LineNumberReader reader = null;
    Pattern pattern;
    Matcher matcher;
    String line=null;
    int i;
    try {
        reader = new LineNumberReader(new FileReader(file));

        while ((line = reader.readLine()) != null) {
            i = reader.getLineNumber();
            String template = "event" + i + ".+end" + i;
            pattern = Pattern.compile(template);
            matcher = pattern.matcher(line);
            if (matcher.find()) {
                System.out.println(line.substring((matcher.start()), matcher.end()));
            }
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

在档案中

event1 arg arg arg end1
event2 arg arg arg end2

并输出相同的

© www.soinside.com 2019 - 2024. All rights reserved.