IO复制文件到另一个地方

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @ClassName: Copy
 * @Description: 文件复制
 * @author snow
 * @date 2021年11月25日
 *
 */
public class Copy {
    
    public static void main(String[] args) throws IOException {
        File inFolder = new File("D:\\TestRead");
        File outFolder = new File("D:\\"+ inFolder.getName()+"copy");
        copyFolder(inFolder,outFolder);
        System.out.println("复制完成");
    }
    
    /**
     * @Title: copyFolder
     * @author snow
     * @date 2021年11月25日
     * @Description: 复制文件夹
     * @param @param inFolder
     * @param @param outFolder
     * @param @throws IOException 参数
     * @return void 返回类型
     * @throws
     */
    private static void copyFolder(File inFolder, File outFolder) throws IOException {
        //遍历文件
        File[] files = inFolder.listFiles();
        for (File file : files) {
            //文件复制
            if (file.isFile()){
                copyFile(file,outFolder);
            }else if (file.isDirectory()){
                //递归复制这个子文件夹
                File newFolder = new File(outFolder,file.getName());
                if (!newFolder.exists()){
                    newFolder.mkdirs();
                }
                //递归子文件夹
                copyFolder(file,newFolder);
            }
        }
    }
    
    /**
     * @Title: copyFile
     * @author snow
     * @date 2021年11月25日
     * @Description: 复制文件
     * @param @param file
     * @param @param outFolder 参数
     * @return void 返回类型
     * @throws
     */
    public static void copyFile(File file, File outFolder){
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        File nf = new File(outFolder, file.getName());

        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            bos = new BufferedOutputStream(new FileOutputStream(nf));
            //一次读取字节
            byte[] bytes = new byte[1024];
            //储存读的字节数
            int num = 0;
            while ((num=bis.read(bytes))!= -1){
                bos.write(bytes,0,num);
            }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if(bis != null){
                        bos.close();
                    }
                    if(bos != null){
                        bos.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
}

 

posted @ 2022-02-15 09:51  白snow  阅读(49)  评论(0编辑  收藏  举报