您的位置:首页 > 其它

复制指定源位置的多级文件夹下所有文件到指定目标位置

2016-05-02 16:05 501 查看
目标:复制指定源位置的所有文件、文件夹到指定的目标位置

分析:

  1.如果指定源位置是文件,则直接复制文件到目标位置。

  2.如果指定源位置是文件夹,则首先在目标文件夹下创建与源位置同名文件夹。

  3.遍历源位置文件夹下所有的文件,修改源位置为当前遍历项的文件位置,目标位置为刚刚上部创建的文件夹位置。

  4.递归调用,回到1.

编程实现

package cn.hafiz.www;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyFolder {
public static void main(String[] args)  throws IOException {
File srcFile = new File("G:\\hafiz");
File desFile = new File("E:\\");
copyFolder(srcFile, desFile);
}

private static void copyFolder(File srcFile, File desFile) throws IOException  {
if(srcFile.isDirectory()) {
//是文件夹,首先在目标位置创建同名文件夹,然后遍历文件夹下的文件,进行递归调用copyFolder函数
File newFolder = new File(desFile, srcFile.getName());
newFolder.mkdir();
File[] fileArray = srcFile.listFiles();
for(File file : fileArray) {
copyFolder(file, newFolder);
}
}else{
//是文件,直接copy到目标文件夹
File newFile = new File(desFile, srcFile.getName());
copyFile(srcFile, newFile);
}
}

private static void copyFile(File srcFile, File newFile) throws IOException {
//复制文件到指定位置
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
byte[] b = new byte[1024];
Integer len = 0;
while((len = bis.read(b)) != -1) {
bos.write(b, 0, len);
}
bis.close();
bos.close();
}
}


至此,多级文件的复制工作就完成了~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: