我从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行,然后是cont和end循环。图像编号是随机的,所以我无法点击其中任何一个。
目前我的代码如下。
while ((line = rd.readLine()) != null) {
if (line.contains("all")) {
line = rd.readLine();
System.out.println(line);
}
}
但如果在'all'之后有一个换行符,我将获得null返回...或有趣的角色UTUYGBLK
答案 0 :(得分:2)
您需要在元素之后循环,直到结果不为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;
}
}
}
}
答案 1 :(得分:1)
然后跳过空白行。
while ((line = rd.readLine()) != null) {
if (line.contains("all")) {
while ((line = rd.readLine()) != null && line.trim().isEmpty());
System.out.println(line);
break;
}
}
答案 2 :(得分:0)
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
,并且在它之后的某个地方确实会出现非空白。
答案 3 :(得分:0)
你可以进入第二个循环来检查空值。
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);
}
或者那种影响。
答案 4 :(得分:0)
如果您的图片名称中包含&#39;全部&#39;你的结果会不正确。修剪线后更好地使用equals()。所以代码看起来像这样:
while ((line = rd.readLine()) != null ) {
if (line.trim().equals("<all>")) {
while ((line = rd.readLine()).isEmpty());
System.out.println(line);
break;
}
}
答案 5 :(得分:-1)
您可以使用方法
line.isEmpty()
处理该案件