从分隔符之间的文件中读取行

时间:2015-10-07 22:57:56

标签: java

例如,如果我有这样的文件:

SECTION 1
Some text
SECTION 2
Some more text
Aother line of text
SECTION 1
Some text
Another line
SECTION 2
Another line here

如何读取每个部分之间的线条(每个部分最多可以有几十行)?这是我现在拥有的:

public static void main(String[] args) {
    BufferedReader br = null;

    try {
        br = new BufferedReader(new FileReader("section_text.txt"));

        String line;

        while (br.readLine() != null) {
            line = br.readLine().trim();
        }

        br.close();

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

2 个答案:

答案 0 :(得分:0)

while (line = br.readLine() != null) {
        if(line.contains("SECTION")){
          // do something with those "SECTION" lines ...
        } else {
          // do something with other non-SECTION lines ...
        }
}

答案 1 :(得分:0)

假设您要将每个部分的行处理为块,请尝试此操作(忽略空部分):

public static void main(String[] args) throws Exception {
    try (BufferedReader br = new BufferedReader(new FileReader("section_text.txt"))) {
        String line, section = null;
        List<String> lines = new ArrayList<>();
        while ((line = br.readLine()) != null) {
            if (line.startsWith("SECTION ")) {
                if (! lines.isEmpty())
                    processSection(section, lines);
                section = line.substring(8).trim();
                lines = new ArrayList<>();
            } else {
                lines.add(line.trim());
            }
        }
        if (! lines.isEmpty())
            processSection(section, lines);
    }
}
private static void processSection(String section, List<String> lines) {
    // code here
}