import java.io.*;
public class TestFinally {
public static void main(String args[]){
FileInputStream in=null;
try{
in =new FileInputStream("myfile.txt");
int b;
b=in.read();
while(b!=-1){
System.out.print((char)b);
b=in.read();
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
System.out.println(e.getMessage());
}
这段代码的红色部分为什么不能少,一少运行,CPU就占用99%??求高手详解....
public class TestFinally {
public static void main(String args[]){
FileInputStream in=null;
try{
in =new FileInputStream("myfile.txt");
int b;
b=in.read();
while(b!=-1){
System.out.print((char)b);
b=in.read();
}
}
catch(FileNotFoundException e){
e.printStackTrace();
}
catch(IOException e){
System.out.println(e.getMessage());
}
这段代码的红色部分为什么不能少,一少运行,CPU就占用99%??求高手详解....
while(b!=-1) {
System.out.print((char)b);
}你不觉得这是个死循环么?CPU持续忙碌,当然负载很高。
while判断的条件 b != -1 一直为true
while(true){
}
跳不出来了。
你没有看过read()函数的API说明吧?while(b!=-1){
System.out.print((char)b);
b=in.read(); // 读取下一个字节,直到流结束则返回 -1
}
//读取下一个字节,直到流结束则返回 -1
所以,加入你的Mytest是:12345
如果去掉in.read()
那么只是在无限循环判断1,所以永远都是无限输出1
而加上的话,
第二次的b=2了,然后3,4,5,到5后面就返回-1了,循环停止。