拷贝指定文件夹到指定目录下
程序员文章站
2022-03-12 09:37:07
...
title: 拷贝指定文件夹到指定目录下
date: 2020-04-05
tags: java
categories: 编程
拷贝代码如下:
主要用到I/O流,File类和递归思想:
import java.io.*;
public class 拷贝目标文件夹到指定目录下 {
public static void main(String[] args) {
// 源文件
File srcFile = new File("G:\\Lw的文本文档");
// 目标地址
File destFile = new File("C:\\");
// 调方法拷贝
copyDir(srcFile,destFile);
}
private static void copyDir(File srcFile, File destFile) {
// 如果它是一个文件那就能用I/O拷贝,递归结束条件
if (srcFile.isFile()){
FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream(srcFile);
String path = (destFile.getAbsolutePath().endsWith("\\")? destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\") +srcFile.getAbsolutePath().substring(3);
out = new FileOutputStream(path);
byte[] bytes = new byte[1024 * 1024];
int readCount = 0;
while((readCount = in.read(bytes))!=-1){
out.write(bytes,0,readCount);
}
out.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (out!=null)
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
if (in!=null)
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return;
}
// 执行到这说明不是文件而是文件夹,所以要先在目标地址上建立对应文件夹
File[] files = srcFile.listFiles();// 这是向下递归的关键
for (File file : files){ // 先把目录创建出来
if (file.isDirectory()){
// 如果它是目录,那就新建它下面的所有目录,用mkdirs
String srcDir = file.getAbsolutePath(); // 源目录是这个值
// 获取目标地址
String destDir = (destFile.getAbsolutePath().endsWith("\\")? destFile.getAbsolutePath():destFile.getAbsolutePath()+"\\") +srcDir.substring(3);
// 创建空文件夹
File newFile = new File(destDir);
if (!newFile.exists()){
newFile.mkdirs();
}
}
//递归
copyDir(file,destFile);
}
}
}