如何在最后一次出现“特定单词”之后打印所有行。在文本文件中

时间:2018-01-10 06:26:57

标签: java file line

我正在使用java编写一个文件,我希望在最后一次出现单词后打印所有行。例如:

> </xs:element>
  </xs:schema>    
  <Tabla1>
  <NUM>1</NUM>
  </Tabla1>
  <Tabladf>
  <NUM>2</NUM>
  </Tabladf>

因此,在上面的示例中,所有数据都应在</xs:schema>

之后打印

编码我使用的:

public static void main(String[] args) throws Exception {
    try (BufferedReader in = new BufferedReader(new FileReader("D:\\Project\\LM2\\supw.xml"))) {
        String line;
        while ((line = in.readLine()) != null) {
            if (line.contains("</xs:schema>"))
                System.out.println(line);
        }

    }
}

请告诉我应该做些什么改变,以获得正确的输出。

2 个答案:

答案 0 :(得分:0)

首先,阅读所有文本并将其放在字符串变量中。

if(str1[0:] in str):

    return "yes"
else:
    return "no"
print(sea("sahil","ah"))

然后,使用正则表达式匹配字符串并找到正则表达式的最后一个匹配的结束索引:

String s = "> </xs:element>\n" +
        "  </xs:schema>    \n" +
        "  <Tabla1>\n" +
        "  <NUM>1</NUM>\n" +
        "  </Tabla1>\n" +
        "  <Tabladf>\n" +
        "  <NUM>2</NUM>\n" +
        "  </Tabladf>"; // instead of writing a string literal, you will read all the lines and put it here

然后,致电int index = 0; Matcher m = Pattern.compile("</xs:schema>\\s*\\n").matcher(s); while (m.find()) { // keep finding new matches until there is not any index = m.end(); } ,您将获得预期的结果!

substring(index)

答案 1 :(得分:-1)

如果您真的只想在特定行之后打印行,则在遇到文件的最后一行之前不能输出任何内容,否则该行可能会在以后出现。所以你必须存储你需要打印的东西。

public static void main(String[] args) throws Exception {
    List<String> lines = new ArrayList<>();
    try (BufferedReader in = new BufferedReader(new FileReader("D:\\Project\\LM2\\supw.txt"))) {
        String line;
        while ((line = in.readLine()) != null) {
            if (line.contains("</xs:schema>")) {
                // print everything after this line, right?
                lines.clear();
            } else {
                lines.add(line);
            }
        }
    }
    // now the file is finished, can print
    lines.forEach(System.out::println);
}