[英]Java read text file and search for a line
我有以下代碼,該代碼通過讀取文件並搜索以subject開頭的行並打印出該行。 但是我只想閱讀包含“主題”的第一行,但是當前它獲取以“主題”開頭的所有行,我該如何配置以使其搜索第一個“主題”並打印該行?
br = new BufferedReader(new FileReader("FilePath"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("Subject ")) {
System.out.println(line);
}
}
使用中斷; 聲明,
br = new BufferedReader(new FileReader("FilePath"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("Subject ")) {
System.out.println(line);
break;
}
}
您應該嘗試使用正則表達式來查找所需模式的所有出現,例如您的情況下的"Subject*\\n"
類的東西。 在Regex上查看此非常好的教程:www.vogella.com/tutorials/JavaRegularExpressions/article.html
您沒有停止循環,因此它將獲取直到最后一行;
嘗試這個
if (line.startsWith("Subject ")) {
System.out.println(line);
break; // break the lop on success match
}
使用ArrayList可以保存以“主題”開頭的每一行,並且可以遍歷所有這些行,可以根據需要使用它
ArrayList<String> list = new ArrayList<String>();
br = new BufferedReader(new FileReader("FilePath"));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
if (line.startsWith("Subject ")) {
list.add(line);
}
}
System.out.println(list.get(0);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.