要在JAVA中实现复制文件夹的内容,由于不知道文件夹的结构,只能使用递归的形式,层层遍历文件夹,进行拷贝的操作。
遍历每层的文件夹时,判断文件列表中的文件是文件夹还是文件,如果是文件的话就创建缓冲流,一读一写,如果是文件夹,则调用mkdir方法即可
下面这个源码,封装成了一个方法,可以直接放到类中去调用。
/**
* 将一个文件夹中的所有文件、文件夹复制到指定的路径
*
* @author bloodarea
* @date 2020/7/12 17:09
*
* @param name 源文件夹的路径
* @param output 粘贴的文件夹地址
* @return void
*/
public static void copyFileDir(File name, File output) {
if(name.isDirectory() && name.exists()){
for (File f : name.listFiles()) {
File newF = new File(output.getPath() + "\\" + f.getName());
if (f.isDirectory()) {
if (!newF.exists()) {
newF.mkdir();
}
copyFileDir(f,newF);
} else if (f.isFile()) {
try( BufferedInputStream bis = new BufferedInputStream(new FileInputStream(f));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newF));
){
byte[] bytes = new byte[1024];
int len;
while ((len = bis.read(bytes)) != -1){
bos.write(bytes,0,len);
}
}catch (IOException e){}
}
}
}
}