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?
但是万一文件里面的内容大于了你一次性能容纳的最大字节 byte[] b=new byte[1024];你if能一次性读完吗?
这个时候肯定就得用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的
我明白了,原来上述代码是错误的,while内的read方法,应该改成有参数的那个