这段代码将向你介绍几个比较常见但需要注意的问题
尽量使用本地配置资源比如 SystemgetProperty(lineseparator) 代替手工输入 \r\n以此解决跨平台问题(WindowsMac等)
如何利用程序读取互联网上的文本资源以及注意其文本编码(Encoding这是本文的要点)
使用 StringBuilder 而不是String 相加获取一个较大的变长文本这主要影响程序性能而不是功能
功能极其有限但对于初学者肯定有其碰壁之处使用该包装好的类可使用如下方式获取互联网文本资源
WebClient wc = new WebClient();
String s = wcgetContent( utf null); Systemoutprintln(s);
如下是WebClient类的源码
package ;
import URL; import URLConnection; import javaioBufferedReader; import javaioIOException; import javaioInputStreamReader;
public class WebClient{
private static String _newLine = SystemgetProperty(lineseparator);
public WebClient(){
}
public String getContent(String url String oriEncoding String targetEncoding) throws IOException{
URL u = new URL(url);
URLConnection uc = uopenConnection();
BufferedReader in;
if(oriEncoding == null || oriEncodinglength() == ){ in = new BufferedReader(new InputStreamReader(ucgetInputStream()));
}
else{
in = new BufferedReader(new InputStreamReader(ucgetInputStream() oriEncoding));
}
String line;
StringBuilder sb = new StringBuilder();
while((line = inreadLine()) != null){ sbappend(line); sbappend(_newLine);
}
if(targetEncoding == null || targetEncodinglength() == ){ return sbtoString();
}
return new String(sbtoString()getBytes() targetEncoding);
}
}