這段代碼將向你介紹幾個比較常見但需要注意的問題
盡量使用本地配置資源比如 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);
}
}
From:http://tw.wingwit.com/Article/program/Java/hx/201311/26959.html