本帖最后由 张向辉 于 2013-2-15 20:20 编辑
先看这一段代码:
import java.io.IOException;
<BR>import java.io.InputStream;
import java.net.URL;
public class TestStream {
public static void main(String args[]){
try {
URL host = new URL("http://www.baidu.com");
InputStream in = host.openStream();
in.read();
in.close();
System.out.println("asscii: "+in.read());
} catch (IOException e) {
e.printStackTrace();
}
}
}
打印结果: asscii: -1
我读取数据后,关闭了输入流,继续读,它却没有抛异常,不过读取结果为-1。再看这段代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class TestStream {
public static void main(String args[]){
try {
URL host = new URL("http://www.baidu.com");
BufferedReader reader = new BufferedReader( new InputStreamReader(host.openStream()));
reader.read();
reader.close();
System.out.println("asscii: "+reader.read());
} catch (IOException e) {
e.printStackTrace();
}
}
}
结果这里关闭流后再读就抛异常了。InputStream关闭流后再读返回结果为 -1 ,BufferedReader 关闭流后再读抛异常,为什么呢 |