【发布时间】:2013-11-21 22:05:08
【问题描述】:
我正在做一个应用程序,它应该将整个 website-html 文本放入字符串中。 然后我想使用 System.out.println 来显示该字符串的某个片段。我的代码
import java.net.*;
import java.io.*;
public class URLConnectionReader {
public static void main(String[] args) throws Exception {
URL oracle = new URL("www.example-blahblahblah.com");
BufferedReader in = new BufferedReader(
new InputStreamReader(oracle.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null)
System.out.println(inputLine.substring(inputLine.indexOf("<section class=\"horoscope-content\"><p>")+1, inputLine.lastIndexOf("</p")));
in.close();
}
}
它应该显示下面键入的文本:
<section class="horoscope-content">
<p>Text text text text</p>
而不是我有这个:
线程“主”java.lang.StringIndexOutOfBoundsException 中的异常:字符串索引超出范围:-1 在 java.lang.String.substring(未知来源) 在 URLConnectionReader.main(URLConnectionReader.java:14)
我该怎么办?
【问题讨论】:
-
indexOf和lastIndexOf如果找不到字符,则返回-1。 -
您对 indexOf 的第二次调用返回 -1,这意味着未找到子字符串。打印整个字符串以查看其内容。我怀疑您在调用 substring 时要查找的文本被分成多行(因此分成不同的字符串)。
-
您应该使用
contains()来检查短语,然后再将它们的位置用作索引。 -
表示你匹配的字符串("
")。如果并且仅当找到您的字符串时,它将返回它的索引。否则它将始终返回-1。因为没找到,是不是打算在最后加上“
”?
-
添加到@HunterMcMillen 的评论;第一步是验证您正在寻找的行是否确实存在于您从服务器获得的响应中。
标签: java