大家请看下面代码。这个代码没有问题,但如果我用scanner代替去读取流的话就会出现乱码,为什么呢?java的io流很复杂,不知道应该怎么根据不同情况去选择io流呢?import java.io.*;
import java.net.*;
import java.util.Scanner;
/**
* Example program from Chapter 2
* Programming Spiders, Bots and Aggregators in Java
* Copyright 2001 by Jeff Heaton
*
* This program uses the standard Java URL class to open a
* connection to a web page and download the contents.
*
* @author Jeff Heaton
* @version 1.0
*/
class GetURL
{ /**
* This method will display the URL specified by the parameter.
*
* @param u The URL to display.
*/
static protected void getURL(String u)
{
URL url;
InputStream is;
InputStreamReader isr;
BufferedReader r;
String str; try
{
System.out.println("Reading URL: " + u );
url = new URL(u);
is = url.openStream();
isr = new InputStreamReader(is);
r = new BufferedReader(isr);
do
{
str = r.readLine();
if(str!=null)
System.out.println( str );
} while( str!= null );
}
catch(MalformedURLException e)
{
System.out.println("Must enter a valid URL");
}
catch(IOException e)
{
System.out.println("Can't connect");
}
} /**
* Program entry point.
*
* @param args Command line arguments. Specified the URL to download.
*/
static public void main(String args[])
{
getURL("http://finance.people.com.cn/GB/70846/16544301.html");
}
}
import java.net.*;
import java.util.Scanner;
/**
* Example program from Chapter 2
* Programming Spiders, Bots and Aggregators in Java
* Copyright 2001 by Jeff Heaton
*
* This program uses the standard Java URL class to open a
* connection to a web page and download the contents.
*
* @author Jeff Heaton
* @version 1.0
*/
class GetURL
{ /**
* This method will display the URL specified by the parameter.
*
* @param u The URL to display.
*/
static protected void getURL(String u)
{
URL url;
InputStream is;
InputStreamReader isr;
BufferedReader r;
String str; try
{
System.out.println("Reading URL: " + u );
url = new URL(u);
is = url.openStream();
isr = new InputStreamReader(is);
r = new BufferedReader(isr);
do
{
str = r.readLine();
if(str!=null)
System.out.println( str );
} while( str!= null );
}
catch(MalformedURLException e)
{
System.out.println("Must enter a valid URL");
}
catch(IOException e)
{
System.out.println("Can't connect");
}
} /**
* Program entry point.
*
* @param args Command line arguments. Specified the URL to download.
*/
static public void main(String args[])
{
getURL("http://finance.people.com.cn/GB/70846/16544301.html");
}
}
scanner是扫描,如果格式不一致那么肯定会乱码。
格式匹配正确,那么是不会有乱码的(对于如何使用流,你觉得那种流熟悉就使用哪种。能使用就行)static protected void getURL2(String u) {
URL url;
InputStream is;
Scanner scanner = null;
try {
url = new URL(u);
is = url.openStream();
scanner = new Scanner(is, "GBK");//编码匹配
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} catch (MalformedURLException e) {
System.out.println("Must enter a valid URL");
} catch (IOException e) {
System.out.println("Can't connect");
}
}