Java:复制文件夹及子文件

来源:互联网 发布:根据网络安全法的规定 编辑:程序博客网 时间:2024/05/21 06:33
package stream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;public class TestStream {    public static void main(String[] args) {        copyFolder("d:/lol","e:/profiles/lol");    }    /**     * @param srcFile 源文件     * @param destFile 目标文件     */    public static void copyFile(String srcPath, String destPath) {        File srcFile = new File(srcPath);        File destFile = new File(destPath);        //缓存区,一次性读取1024字节        byte[] buffer = new byte[1024];        try (                FileInputStream fis = new FileInputStream(srcFile);                FileOutputStream fos = new FileOutputStream(destFile);            )        {            while (true) {                //实际读取的长度是actuallyReaded,有可能小于1024                  int actuallyReaded = fis.read(buffer);                // -1表示没有可读的内容了                if(-1==actuallyReaded)                    break;                fos.write(buffer, 0, actuallyReaded);            }        } catch (IOException e) {            e.printStackTrace();        }    }    /**     * @param srcPath  源文件夹     * @param destPath 目标文件夹     */    public static void copyFolder(String srcPath, String destPath) {        File srcFolder = new File(srcPath);        File destFolder = new File(destPath);        //源文件夹不存在        if(!srcFolder.exists())            return;        //源文件夹不是一个文件夹        if(!srcFolder.isDirectory())            return;        //目标文件夹是一个文件        if(destFolder.isFile())            return;        //目标文件夹不存在,则创建一个        if(!destFolder.exists())            destFolder.mkdirs();        //遍历源文件夹        File[] files = srcFolder.listFiles();        for (File f : files) {            //如果是文件就复制            if(f.isFile()) {                File newDestFile = new File(destFolder,f.getName());                copyFile(f.getAbsolutePath(), newDestFile.getAbsolutePath());            }            //如果是文件夹,就递归            if(f.isDirectory()) {                File newDestFolder = new File(destFolder,f.getName());                copyFolder(f.getAbsolutePath(), newDestFolder.getAbsolutePath());            }        }    }}
0 0
原创粉丝点击