Java:在读取文本文件时,如何读取包含特定字符串的特定行?

时间:2016-03-25 19:53:04

标签: java

        try(BufferedReader br = new BufferedReader(new FileReader("MANIFEST.MF"))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();

        while (line != null) {
            sb.append(line);
            sb.append(System.lineSeparator());
            line = br.readLine();
        }
        String everything = sb.toString();
        System.out.println(everything);

这是我用来阅读文件中的所有文本,我很好奇我怎么能改变它,以便我读取包含例如“Main-Class”的特定行。

提前致谢!

2 个答案:

答案 0 :(得分:0)

检查你的线变量是否包含你正在寻找的字符串,然后退出while循环...或者用你想做的任何事情。您可能还希望将代码更改为...更简洁,更易读。

String line = null;

    while ((line = br.readLine()) != null) {
        sb.append(line);
        sb.append(System.lineSeparator());
    }

答案 1 :(得分:0)

找到第一行包含" Main-Class":

try ( BufferedReader reader = new BufferedReader( new FileReader("MANIFEST.MF")) ) {

  String line = null;
  while ( ( line = reader.readLine() ) != null ) {
    if ( line.contains("Main-Class") ) break;
  }

  if ( line != null ) {
    // line was found
  } else {
    // line was not found
  }
}

查找包含" Main-Class":

的所有行
StringBuilder matchedLines = new StringBuilder();
try ( BufferedReader reader = new BufferedReader( new FileReader("MANIFEST.MF")) ) {

  String line = null;
  while ( ( line = reader.readLine() ) != null ) {
    if ( line.contains("Main-Class") ) {
      matchedLines.append(line);
      matchedLines.append(System.lineSeparator());
    }
  }
}
// ...
System.out.println("Matched Lines:");
System.out.println(matchedLines.toString());