这段代码将向你介绍几个比较常见但需要注意的问题: 1,尽量使用本地配置资源,比如 System.getProperty("line.separator") 代替手工输入 “\r\n”,以此解决跨平台问题(Windows、Mac等)。
) K! ^' E. f' | 2,如何利用程序读取互联网上的文本资源,以及注意其文本编码(Encoding,这是本文的要点)。) n/ `2 E3 N7 {$ s( Z8 r/ c
3,使用 StringBuilder 而不是“String 相加”获取一个较大的变长文本,这主要影响程序性能,而不是功能。# V$ `; C- o% i" A
功能极其有限,但对于初学者肯定有其碰壁之处,使用该包装好的类,可使用如下方式获取互联网文本资源:
9 Y B; e% C9 X, x$ ^ WebClient wc = new WebClient();
2 u- f X/ M7 Y7 U9 m String s = wc.getContent("http://localhost:8088/index.jsp", "utf-8", null); System.out.println(s);! E$ M: Q7 D/ ]7 s
如下是WebClient类的源码:
' ?6 _; Q5 i" \ L; u0 g7 V( n package queen.net;
$ q! ` V1 r7 D! h9 z: v0 l import java.net.URL; import java.net.URLConnection; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader;
$ o' x+ @% T9 Y! } d( N6 x8 H# m public class WebClient{) M* x0 O, T" h# d
private static String _newLine = System.getProperty("line.separator");& `3 }, w. ^0 M; G0 H6 J: E
public WebClient(){
0 Y) o/ b8 [% c2 U5 ~! g }; `/ E1 y: H7 H( m
public String getContent(String url, String oriEncoding, String targetEncoding) throws IOException{) b4 \" u$ a: m. ?* c9 A6 s
URL u = new URL(url);
/ @- ^8 O. k$ ]) A9 P) U URLConnection uc = u.openConnection();
1 D, ?( Y' I5 b9 @" Y( ]' c A BufferedReader in;
' ]2 `. f+ s" P, T% c if(oriEncoding == null || oriEncoding.length() == 0){ in = new BufferedReader(new InputStreamReader(uc.getInputStream()));+ B; P! C- Y* u* `* q. e
}% S, Y2 Y& ~& f& N
else{
4 K& o) L( ]: v& t in = new BufferedReader(new InputStreamReader(uc.getInputStream(), oriEncoding));8 X/ ?$ o0 L x. @* A
}( S1 i0 k* \4 y% n
String line;1 m' c5 Q0 a2 I: i+ l9 \ V* m
StringBuilder sb = new StringBuilder();
- x; z+ e, L) k; U# |" h1 w1 U while((line = in.readLine()) != null){ sb.append(line); sb.append(_newLine);
7 z6 Y. }4 G' n) a" u( { }8 G2 z9 T$ ?9 ~) R" Q3 e
if(targetEncoding == null || targetEncoding.length() == 0){ return sb.toString();
( k; ~* v$ l6 K; ~' B5 s: d, Z }! w( B- T9 N5 N: l( [
return new String(sb.toString().getBytes(), targetEncoding);6 c# j9 @) ~. ?( k3 d( Y7 E
}9 k. @+ Z) K$ h9 P/ h9 s
} |