[英]Java How to find a specific line after a specific string?
我從BufferedReader獲得了文本,我需要在特定字符串后獲取特定行
這是文本,例如:
<img src="https://example.com/image1.jpg">
<img src="https://example.com/image2.jpg">
<img src="https://example.com/image3.jpg">
<img src="https://example.com/image4.jpg">
<all>
<img src="https://example.com/image9.jpg">
<img src="https://example.com/image11.jpg">
<img src="https://example.com/image15.jpg">
換行示例
<img src="https://example.com/image1.jpg">
<img src="https://example.com/image2.jpg">
<img src="https://example.com/image3.jpg">
<img src="https://example.com/image4.jpg">
<all>
<img src="https://example.com/image9.jpg">
<img src="https://example.com/image11.jpg">
<img src="https://example.com/image15.jpg">
其他角色的例子
<img src="https://example.com/image1.jpg">
<img src="https://example.com/image2.jpg">
<img src="https://example.com/image3.jpg">
<img src="https://example.com/image4.jpg">
<all>
UTUYGBLK
<img src="https://example.com/image9.jpg">
<img src="https://example.com/image11.jpg">
<img src="https://example.com/image15.jpg">
我只希望在“ all”之后的img src行,然后繼續並結束循環。 圖片編號是隨機的,因此我無法打中任何一個。
目前我的代碼如下。
while ((line = rd.readLine()) != null) {
if (line.contains("all")) {
line = rd.readLine();
System.out.println(line);
}
}
但是如果在'all'之后有換行符,我將得到一個null回報...或有趣的字符UTUYGBLK
您將需要在元素之后循環,直到結果不為null為止。 下面的代碼應防止在文件結束后讀取行,並且在讀取后顯示第一行后也應停止。
boolean loop = true;
// global loop
while ((line = rd.readLine()) != null && loop) {
// line with "all" in it is found?
if(line.contains("all")) {
// Continue going through the input until end of input
while((line = rd.readLine()) != null && loop) {
// When the line is not empty you have found the line after all!
if(!line.isEmpty()) {
System.out.println(line);
// to stop the loops
loop = false;
}
}
}
}
然后,只需跳過空白行即可。
while ((line = rd.readLine()) != null) {
if (line.contains("all")) {
while ((line = rd.readLine()) != null && line.trim().isEmpty());
System.out.println(line);
break;
}
}
String line = "";
while (!line.contains("all"))
line = rd.readLine();
line = rd.readLine();
while ("".equals(line.trim()))
line = rd.readLine();
return line;
//or System.out.println(line);
這將:
line
設置為空字符串。 all
行的行。 這是基於這樣的假設,即實際上將有一行包含all
,並且在它之后的某處確實將有一個非空白。
您可以進入第二個循環以檢查是否為空。
while ((line = rd.readLine()) != null) {
if (line.contains("all")) {
while ((line = rd.readLine()) == null || line.isEmpty()) {
//keep looping while line is null
//check if it is no longer ready to avoid infinite loop
if (!rd.ready()) {break;}
}
//line should not be null here
System.out.println(line);
}
或有什么影響。
如果使用contains()(如果您的圖像名稱包含“ all”,則結果將不正確)。 修剪線后最好使用equals()。 因此,代碼將如下所示:
while ((line = rd.readLine()) != null ) {
if (line.trim().equals("<all>")) {
while ((line = rd.readLine()).isEmpty());
System.out.println(line);
break;
}
}
您可以使用方法
line.isEmpty()
處理這種情況
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.