天天看點

Java遞歸拷貝檔案夾

拷貝檔案或檔案夾

/**
 * 拷貝檔案
 *
 * @param source    源檔案
 * @param target    目标檔案
 */
public void copyFile(String source, String target) {
    // 源檔案
    File sourceFile = new File(source);
    if (!sourceFile.exists()) {
        return;
    }

    // 目标檔案
    File targetFile = new File(target);

    // 檔案拷貝
    if (sourceFile.isFile()) {
        copyFromChanel(sourceFile, targetFile);
        return;
    }

    // 檔案夾拷貝
    if (!targetFile.exists()) {
        targetFile.mkdirs();
    }
    for (File file: sourceFile.listFiles()) {
        copyFile(file.getAbsolutePath(), target + File.separator + file.getName());
    }

}
           

利用檔案管道拷貝檔案

/**
 * 利用檔案管道拷貝檔案
 *
 * @param source    源檔案
 * @param target    目标檔案
 */
public void copyFromChanel(File source, File target) {

    // 檔案流
    FileInputStream fis = null;
    FileOutputStream fos = null;

    // 檔案管道
    FileChannel fci = null;
    FileChannel fco = null;
    try {

        // 檔案流
        fis = new FileInputStream(source);
        fos = new FileOutputStream(target);

        // 檔案管道
        fci = fis.getChannel();
        fco = fos.getChannel();

        // 連接配接兩個通道,并且從fci通道讀取,然後寫入fco通道
        fci.transferTo(0, fci.size(), fco);

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

版權聲明:本文為CSDN部落客「weixin_33964094」的原創文章,遵循CC 4.0 BY-SA版權協定,轉載請附上原文出處連結及本聲明。

原文連結:https://blog.csdn.net/weixin_33964094/article/details/91918469