嘿大家我有一个奇怪的问题, 我想从网站解析 channel 模板。 什么有效: 解析文件并从头开始剪切(例如仅德国 channel ),但从行尾剪切总是以索引超出范围 -1 异常结束 不知道为什么。
免责声明:这只是一个虚拟文件, channel 无法正常工作! 所以不要排除免费电视之类的东西。
public static void main(String[] args) throws Exception {
{
String url = "http://www.vjackson.info//live/index";
final String USER_AGENT = "VAVOO/1.51";
URL obj = new URL(url);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
final String trimFromLine = "no mather whats in here it dont work";
final String searchKey = "#EXTINF:-1 tvg-name=\"13TH STREET FHD";
String result = "";
// Send post request
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine = "";
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
if (response.toString().contains(searchKey)) {
result=response.toString().substring(response.toString().indexOf(searchKey));
String result2 = result.substring(0, result.indexOf(trimFromLine));
}
}
in.close();
System.out.println(result);
//print result
}
}
}
最佳答案
当 result
中未找到 trimFromLine
时,
result.indexOf(trimFromLine)
返回 -1
。如果您尝试运行 String.substring(0, -1)
,您将得到与您所看到的相同的 StringIndexOutOfBoundsException
。
在尝试调用此方法之前,您应该检查是否属于这种情况:
int indexOfTrim = result.indexOf(trimFromLine);
String result2;
if (indexOfTrim > -1) {
result2 = result.substring(0, indexOfTrim);
}
我怀疑 result2
赋值导致了该问题。将结果与 trimFromLine
进行比较,看看会得到什么。另请检查 result.indexOf(trimFromLine)
的结果。
关于java - 字符串修剪异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52856298/