1. 程式人生 > >jdk1.7 nio實現檔案拷貝

jdk1.7 nio實現檔案拷貝

主要原理是利用jdk1.7的Files.walkFileTree遍歷檔案樹,再在裡面用Files.copy即可實現高效能jdk new io檔案拷貝.

可以參考如下程式碼:

/**
     * 拷貝標準工程
     * 
     * @param source 源路徑
     * @param target 目標路徑
     * @throws IOException IO異常
     */
    private void doCopyProject(Path source, Path target) throws IOException {
        // 拷貝資料夾目錄
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new CopyDirectoryVisitor(source, target));
    }
package xxx
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.nio.file.DirectoryNotEmptyException;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.BasicFileAttributes;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 資料夾複製
 * 
 * @author 許暢
 * @since JDK1.7
 * @version 2017年10月13日 許暢 新建
 */
public class CopyDirectoryVisitor extends SimpleFileVisitor<Path> {
    
    /** 日誌 */
    private static final Logger LOGGER = LoggerFactory.getLogger(CopyDirectoryVisitor.class);
    
    /** 原始檔 */
    private Path source;
    
    /** 目標檔案 */
    private Path target;
    
    /**
     * 構造方法
     *
     * @param source 原始檔
     * @param target 目標檔案
     */
    public CopyDirectoryVisitor(Path source, Path target) {
        this.source = source;
        this.target = target;
    }
    
    /**
     * 訪問檔案
     * 
     * @param file 檔案路徑
     * @param attributes 屬性
     * @return FileVisitResult
     * @throws IOException IO異常
     */
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException {
        LOGGER.info("Copying " + source.relativize(file));
        Files.copy(file, target.resolve(source.relativize(file)), StandardCopyOption.REPLACE_EXISTING);
        return FileVisitResult.CONTINUE;
    }
    
    @Override
    public FileVisitResult preVisitDirectory(Path directory, BasicFileAttributes attributes) throws IOException {
        Path targetDirectory = target.resolve(source.relativize(directory));
        try {
            LOGGER.info("Copying " + source.relativize(directory));
            Files.copy(directory, targetDirectory, StandardCopyOption.REPLACE_EXISTING);
        } catch (FileAlreadyExistsException e) {
            if (!Files.isDirectory(targetDirectory)) {
                throw e;
            }
        } catch (DirectoryNotEmptyException e) {
            // ignore
        } catch (AccessDeniedException e) {
            // ignore
        }
        return FileVisitResult.CONTINUE;
    }
    
}