IO流实现文件的复制

废话不多说,直接上代码

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

public class MyFileUtil {
    private FileInputStream fis;
    private FileOutputStream fos;

    /**
     * @param fromFile  要复制的文件路径+文件名
     * @param toFile    要保存到的目的文件路径+文件名
     */
    public void FileCopy(String fromFile,String toFile){
        try {
            //实例化文件
            fis=new FileInputStream(fromFile);
            fos=new FileOutputStream(toFile);
            //创建缓冲字节数组
            byte[] buffer=new byte[1024];

            int length;
            while ((length=fis.read(buffer))!=-1){
                fos.write(buffer,0,length);
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(fis!=null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

posted @ 2021-11-24 16:45  Java小羊  阅读(122)  评论(0编辑  收藏  举报