//无论你是否回答了此问题,小弟先感谢你对本人,本问题的关注,谢谢!!package com.ym2005.copy;import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
//这个是我的类,用来把一个文件夹从一个地方复制到另外一个地方。..
public class Mycopy {
//这个方法是用来复制文件的测试可以成功复制
public static void copyFile(File source, File target) throws Exception {
FileInputStream in = new FileInputStream(source);
FileOutputStream out = new FileOutputStream(target);
byte[] a = new byte[2000];
int len = in.read(a);
while (len != -1) {
out.write(a, 0, len);
len = in.read(a);
}
}
//这个方法是用来复制文件夹(包括里面的文件)。-问题是创建不了文件夹.问题就出现在这里...
public static void copyFolder(File source, File target) throws Exception {
System.out.println(source.getAbsolutePath());
if (source.isDirectory()) {
if (source.isFile()) {
copyFile(source, target);
System.out.println("是文件");
} else {
System.out.println("是目录");
source.mkdirs();
}
File[] a = source.listFiles();
for (int i = 0; i < a.length; i++) {
copyFolder(a[i], target);
}
}
} public static void main(String[] args) {
//这里是定义了目标文件夹和源文件夹
File f1 = new File("D:\\a");
File f2 = new File("C:\\");
try {
copyFolder(f1, f2);
} catch (Exception e) {
e.printStackTrace();
}
}}

解决方案 »

  1.   

    // 把拷贝文件,如果新文件不存在,自动创建
        void copy(File src, File dst) throws IOException {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dst);
        
            // Transfer bytes from in to out
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
        }
      

  2.   


    // 递归拷贝文件夹,如果新文件夹不存在则自动创建。
        public void copyDirectory(File srcDir, File dstDir) throws IOException {
            if (srcDir.isDirectory()) {
                if (!dstDir.exists()) {
                    dstDir.mkdir();
                }
        
                String[] children = srcDir.list();
                for (int i=0; i<children.length; i++) {
                    copyDirectory(new File(srcDir, children[i]),
                                         new File(dstDir, children[i]));
                }
            } else {
                // 这个就是一楼给出的方法
                copy(srcDir, dstDir);
            }
        }
      

  3.   

    楼主的方法错误在于,需要判断是否存在再去创建文件夹
    具体看我给的代码中的exists处
      

  4.   

    谢谢masse ,,真的很感谢。