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();
}
}
请问这段代码是什么意思,请同志们把它的执行步骤说明下。、

解决方案 »

  1.   

    我不明白while里面的这段意思,对结果表示不解,恳请知晓的朋友能告诉我下。。
      

  2.   


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

  3.   

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

  4.   

    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(); } }//关闭流
      

  5.   

    b[]里面存的是文件内容转换成的asc码,需要用字符串类型输出才能让大家可读。以下String(byte[] bytes)的javadoc:
    Constructs a new String by decoding the specified array of bytes using the platform's default charset.
      

  6.   

    FileInputStream 是字节流 while你不理解的是  要 -1? new String(); 就是显示字符串,你可以查看api里的构造函数
      

  7.   

    因为是b是byte类型,需要转成string类型来输出
      

  8.   

    哦,原来是调用String构造方法,之前不知道有这个方法。
    谢谢大家的帮助。!