I/O中使用字节数组拷贝文件夹(递归思想)

版权声明:小佳 https://blog.csdn.net/qq_37870901/article/details/81900999

package com.xin02;

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

public class CopyFilesOrDir {
    public static void main(String[] args) throws IOException {
        /*CopyFilesOrDir("D:\\新建文件夹\\7.20demo", "D:\\test\\b");*/
    }
    /**
     * 拷贝文件夹
     * @param beinsrc 开始路径
     * @param endsrc 结束路径
     * @throws IOException
     */
    public static void CopyFilesOrDir(String beinsrc,String endsrc) throws IOException {
        File beinfile = new File(beinsrc);        
        if(beinfile.isFile()) {
            FileByteCopy2(beinsrc,endsrc);
        }
        if(beinfile.isDirectory()) {
            endsrc = endsrc+File.separator+beinfile.getName();
            File endfile = new File(endsrc);
            if(!endfile.exists()) {
                endfile.mkdirs();
            }
            File[] files = beinfile.listFiles();
            if(files!=null) {
                for(File f : files) {
                        CopyFilesOrDir(f.getAbsolutePath(),endsrc);
                }
            }        
        }
    }    
    /**
     * 使用字节数组拷贝文件夹
     * @param beinsrc
     * @param endsrc
     * @throws IOException
     */
    public static void FileByteCopy2(String beinsrc,String endsrc) throws IOException {
        File beinfile = new File(beinsrc);
        File endfile = new File(endsrc);
        FileInputStream fi = new FileInputStream(beinfile);
        FileOutputStream fo = new FileOutputStream(endfile+File.separator+beinfile.getName());
        byte[] b = new byte[1024];
        int len;
        while((len=fi.read(b))!=-1) {
            fo.write(b, 0, len);
            fo.flush();
        }
        fo.close();
        fi.close();
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37870901/article/details/81900999
今日推荐