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

复制文件夹问题
下面是代码 但是只是复制1文件夹下面所有文件而没有1文件夹, 怎么把1文件夹整个复制过去
public static void main(String[] args) {
TestIO1 io = new TestIO1();
io.copyFolder("C:/1","D:/4");

}
public void copyFolder(String file,String path) {
try {
File a = new File(file);
File[] allfile = a.listFiles();
File newpath = new File(path);
if (!newpath.exists()) {
newpath.mkdirs();
}
File temp = null;
for (int m = 0; m < allfile.length; m++) {
if (file.endsWith(File.separator)) {
temp = new File(file + allfile[m].getName());
} else {
temp = new File(file + File.separator + allfile[m].getName());
}
if (allfile[m].isFile()) {
FileInputStream fis = new FileInputStream(temp);
FileOutputStream fos = new FileOutputStream(path+"/"+ temp.getName());
byte[] b = new byte[1024];
int i = 0;
while ((i = fis.read(b)) != -1) {
fos.write(b, 0, i);
}
fos.flush();
fis.close();
fos.close();

}
if(allfile[m].isDirectory()){
copyFolder(file+"/"+allfile[m].getName(),path+"/"+allfile[m].getName());
}
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e2) {
e2.printStackTrace();
}
}

------解决方案--------------------
File[] allfile = a.listFiles();

你已经决定,只复制下面的文件了。所以你应该判定,如果复制的是目录,先创建那个目录,然后再...