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

IO流中最常见的while循环
Java code

package io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class TestIO{
    public static void main(String args[]) throws IOException{
        try{
            FileInputStream fis=new FileInputStream("D://1.txt");
            FileOutputStream fos=new FileOutputStream("D://2.txt");
        
            byte[] b=new byte[1024];
            int read=fis.read(b);          //这时候不是已经将1.txt中的所有数据读出来了吗?
            System.out.println("--------"+read);
            while(read!=-1){              //为什么还要用while?  将while换成if发现结果是一样的!
                fos.write(b,0,b.length);  
                read=fis.read();      //如果1.txt数据已经全部读出,则此时read为-1,跳出while
            }
            fis.close();
            fos.close();
        }catch(IOException e){
            e.printStackTrace();
        }
        
    }
}



求解释,越详细越好,为什么都在用while?


------解决方案--------------------
这个
int read=fis.read(b); //这时候不是已经将1.txt中的所有数据读出来了吗?
这里只是读取了最多1024字节(如果没有读取到文件尾),read是实际读取的字节数
while(read!=-1){ //为什么还要用while? 将while换成if发现结果是一样的!
while是保证一定将文件读取完,换成if只有在文件小于1024字节时是一样的结果
read=fis.read(); //如果1.txt数据已经全部读出,则此时read为-1,跳出while
对的,如果上一次已经读取到文件尾,此次已经没有数据可读了,那么会返回-1的