日期:2014-05-20  浏览次数:20728 次

用io流复制文件夹(包括文件夹里的文件)--出现的问题,无法创建文件夹


//无论你是否回答了此问题,小弟先感谢你对本人,本问题的关注,谢谢!!

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();
}
}

}


------解决方案--------------------
// 把拷贝文件,如果新文件不存在,自动创建
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();
}