[英]How to read text file line by line in Java and exclude some line which start with specific string
[英]Java: When reading a text file, how can i read that specific line which contains a certain string?
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”的特定行。
提前致謝!
檢查行變量是否包含要查找的字符串,然后退出while循環...或對該行執行任何操作。 您可能還想將代碼更改為此...更加簡潔和易讀。
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
}
要查找包含“ 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());
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.