---
title: "文件Copy，什么方式才最快呀~~"
author: "daimojingdeyu"
date: "2010-05-17T23:31:08Z"
tags: []
categories: ["编程语言"]
slug: "copy"
draft: false
lastmod: "2010-05-17T23:31:08Z"
id: 668369
url: "https://daimojingdeyu.iteye.com/blog/668369"
---

闲逛CSDN，发现有人找文件Copy的方法，顺手解答了一下，有点感觉，所以在此博客上记录一下，备检。

都在说使用transferTo是调用的操作系统的接口，速度最快，这里也用一下，至于到底多快，没有实测过。

```
    public static void copyFiles(File src, File dest) {
        // 系统的隐藏文件或是源文件不存在，不进行Copy
        if (src.isHidden() || !src.exists()) {
            return;
        }

        // 对于文件夹需要递归的Copy
        if (src.isDirectory()) {
            if (!dest.exists()) {
                dest.mkdirs();
            }
            File[] files = src.listFiles();
            for (int i = 0; i < files.length; i++) {
                File destfile = new File(dest.getAbsolutePath() + File.separator + files[i].getName());
                copyFiles(files[i], destfile);
            }
        } else {
            try {
                File destfile = dest;
                // 对于源文件是文件，而目标文件是目录的情况，将源文件以同名文件的形式Copy到目标目录下
                if (dest.isDirectory()) {
                    destfile = new File(dest.getAbsolutePath() + File.separator + src.getName());
                }
                FileChannel sfc = new FileInputStream(src).getChannel();
                FileChannel dfc = new FileOutputStream(destfile).getChannel();
                sfc.transferTo(0, sfc.size(), dfc);

                sfc.close();
                dfc.close();
                
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            } 
        }
    }
```