转自http://www.51testing.com/html/85/258885-811659.html
BufferedReader 类
BufferedReader 由Reader类扩展而来,提供通用的缓冲方式文本读取,而且提供了很实用的readLine,读取一个文本行,从字符输入流中读取文本,缓冲各个字符,从而提供字符、数组和行的高效读取。
一般用法:
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("ming.txt")));
String data = null;
while((data = br.readLine())!=null)
{
System.out.println(data);
}
示例如下:
public static String getHtml(String url) throws IOException {
String source ="";
String line ="";
URL _url = new URL(url);
InputStream inStream = _url.openStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inStream,"UTF-8"));
while((line = bufferedReader.readLine())!=null) {
source += line;
}
return source;
}
InputStreamReader 类
是字节流通向字符流的桥梁,封裝了InputStream在里头, 它以较高级的方式,一次读取一个一个字符,以文本格式输入 / 输出,可以指定编码格式;
一般用法:
InputStreamReader isr = new InputStreamReader(new FileInputStream("ming.txt"));
while((ch = isr.read())!=-1)
{
System.out.print((char)ch);
}
示例如下:
public static String getHtmlSource( String url) throws MalformedURLException, IOException {
URLConnection uc = new URL(url).openConnection();
uc.setConnectTimeout(10000);
uc.setDoOutput(true);
InputStream in = new BufferedInputStream(uc.getInputStream());
InputStreamReader rd = new InputStreamReader(in,"gb2312");
int c = 0;
StringBuffer temp = new StringBuffer();
while((c = rd.read())!= -1){
temp.append((char)c);
}
in.close();
return temp.toString();
}