文件的拷贝

文件拷贝需要以下几个步骤:

1.建立联系:两个File对象,源头和目的地

2.选择流:

文件输入流:InputStream FileInputStream

文件输出流:OutputStream FileOutputStream

3.操作:拷贝

byte[] car=new byte[1024];+read

whrite+flush

4.释放资源:关闭两个流

File是可以创建文件和文件夹的,但是注意,文件我们是可以通过流去读取的,文件夹不可以;拷贝过程其实很简单,我们在文件读写操作时,都用到了byte数组和String字符串。

读取操作是用byte数组接收,转化为String字符串便于输出

假设我的数组长度为8,即8字节 byte[] buffer=new byte[8];

定义一个int变量,得到实际读取的字节数 int len=0;

用一个循环来不断的读取数据,当文件中数据都读完以后,is.read会返回(-1),那么只要没返回-1,就会一直不停的读取数据,每次读取的长度就是设置的byte数组的长度,也就是这里的8

while(-1!=(len=is.read(buffer))){

String info=new String(buffer,0,len);

}

也就是这个buffer数组,是会一直往里面装东西的,如果我的文件是18个字节,那么就需要用到3次这个数组,数组中的数据是会不断被覆盖的,当然定义一个大空间的byte数组可以避免这种问题,一般读取设置byte数组大小为1024

读取操作就完成了,可以输出到控制台便于查看

写出操作是将String转化为byte,写入文件

String str="qaz";

byte[] buffer=str.getBytes();

os.write(buffer,o,buffer.length);

这里的byte数组不设置大小

那么读写操作放在一起,其实代码更加精简

byte[] buffer=new byte[1024];

int len=0;

while(-1!=(len=is.read(buffer))){

os.write(buffer,0,buffer.length);

//os.write(buffer);也可行

}

样例:

复制代码
public class Demo02 {  
    public static void main(String[] args) throws IOException {  
          
        File src=new File("F:/Picture/1.jpg");  
        File dest=new File("F:/Picture/copy1.jpg");  
          
        InputStream is=null;  
        OutputStream os=null;  
          
        byte[] buffer=new byte[1024];  
        int len=0;  
          
        try {  
            is = new FileInputStream(src);  
            os = new FileOutputStream(dest);  
  
            //从文件夹读取读取  
            while (-1 != (len=is.read(buffer))) {  
                //写出到文件夹  
                os.write(buffer, 0, len);  
            }  
            //强制刷出  
            os.flush();  
          
        }finally{  
            //先打开的后关闭  
            if(os!=null){  
                os.close();  
            }  
              
            if(is!=null){  
                is.close();  
            }  
        }  
    }  
}  
复制代码
原文地址:https://www.cnblogs.com/chinaifae/p/10328831.html