【Java】复制多级文件夹
package LearnJava15;
import java.io.*;
public class CopyFoldersDemo {
public static void main(String[] args) throws IOException {
// 数据源
File srcFile=new File("D:\\MyProject\\Java\\Demo2\\test\\test2");
// 目的源
File destFile=new File("D:\\MyProject\\Java\\Demo2\\myCharSTream");
copyFolder(srcFile,destFile);
}
//复制文件夹
private static void copyFolder(File srcFile, File destFile) throws IOException {
if (srcFile.isDirectory()){
String srcFileName = srcFile.getName();
File newFolder = new File(destFile,srcFileName);
// 判断是否存在
if (!newFolder.exists()){
newFolder.mkdir();
File[] filesArray = srcFile.listFiles();
for (File file:filesArray){
copyFile(file,newFolder);
}
}else {
// 如果是文件,直接使用字节流
File newFile =new File(destFile,srcFile.getName());
copyFile(srcFile,newFile);
}
}
}
// 复制文件
private static void copyFile(File srcFile, File destFile) throws IOException {
BufferedInputStream bis=new BufferedInputStream(new FileInputStream(srcFile));
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(destFile));
byte[] bys=new byte[1024];
int len;
while ((len=bis.read(bys))!=-1){
bos.write(bys,0,len);
}
bos.close();
bis.close();
}
}
本文来自博客园,作者:木子欢儿,转载请注明原文链接:https://www.cnblogs.com/HGNET/p/16196106.html