public static String getContent(String strUrl,String fileOutPath,String fileName) {
try {
URL url = new URL(strUrl);
BufferedReader br = new BufferedReader(new InputStreamReader(url.openStream(),"gb2312"));
String s = "";
StringBuffer sb = new StringBuffer("");
while ((s = br.readLine()) != null) {
sb.append(s);
}
br.close();
String tem=sb.toString();
StringBuilder sbu = new StringBuilder("");
int i=1;
int begin;
int end;
do{
begin=tem.indexOf(">",i);
end=tem.indexOf("<",begin);
sbu.append(tem.substring(begin+1, end)+"\r\n");
i=end+1;
}while(i<tem.length()-6);
String outputFile= fileOutPath+fileName+".txt";
FileOutputStream fos=new FileOutputStream(outputFile);
fos.write(sbu.toString().getBytes("gb2312"));
fos.close();
return sbu.toString();
} catch (Exception e) {
return "error open url:" + strUrl;
}
}
在这段程序中若把while(i<tem.length()-6);改为while(i<tem.length());就无法生成txt文件,这是为什么?还有就是这段代码该如何改进?

该博客介绍了如何使用Java从HTML网页中提取文本信息并将其存储为TXT文件。通过创建URL对象,读取网页内容,并进行特定字符截取来实现文本提取。然而,代码中存在一个问题:当`while(i<tem.length()-6)`改为`while(i<tem.length())`时,程序无法生成TXT文件。博主探讨了这一现象的原因,并提出了代码改进的建议。

2677

被折叠的 条评论
为什么被折叠?



