日期:2014-05-20  浏览次数:20659 次

求助:IO流的小问题。
Java code
class test1{
    public static void main(String[] args) throws IOException {
        FileInputStream fi=new FileInputStream("D:/demo.txt");
        int n=fi.available();
        byte b[]=new byte[n];
        while(fi.read(b)!=-1){
            System.out.println(new String(b));
        }
        fi.close();
    }
}

请问这段代码是什么意思,请同志们把它的执行步骤说明下。、

------解决方案--------------------
Java code

class test1{
    public static void main(String[] args) throws IOException {
        FileInputStream fi=new FileInputStream("D:/demo.txt");
        int n=fi.available();[color=#FF0000]//demo.txt文件大小[/color]
        byte b[]=new byte[n];[color=#FF0000]//创建n个长度的字节数组[/color]
        while(fi.read(b)!=-1){[color=#FF0000]//读取demo.txt文件,存入b中。如果fi.read(b)返回-1,表示没有数据[/color]
            System.out.println(new String(b));//把字节数组转换成字符串打印出来
        }
        fi.close();
    }
}

------解决方案--------------------
class test1
{ public static void main(String[] args) throws IOException 
{ FileInputStream fi=new FileInputStream("D:/demo.txt"); //创建一个对象
int n=fi.available();读取"D:/demo.txt"输入流字节数的估计值
 byte b[]=new byte[n];//把txt文件以字节的形式存入byte[] 数组
 while(fi.read(b)!=-1)//直到把数组当中的字节全部读完,读到-1时,就说明读完了
{ System.out.println(new String(b)); } //以字符串的形式把txt文件输出来
fi.close(); } }//关闭流
------解决方案--------------------
探讨

谢谢楼上,我大概了解了。
但问题是,它最后为什么要用 new String(b)来显示内容呢?

------解决方案--------------------
FileInputStream 是字节流 while你不理解的是 要 -1? 

new String(); 就是显示字符串,你可以查看api里的构造函数