import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Copy {
public static void main(String[] args) throws IOException {
String resourcePath = "D:\\img";
String targetPath = "D:\\test02";
copy(resourcePath,targetPath);
}
/**
* 复制文件夹和其中的文件
* @param resourcePath
* 源路径
* @param targetPath
* 目标路径
* @throws IOException
*/
public static void copy(String resourcePath, String targetPath) throws IOException {
//源文件
File resource = new File(resourcePath);
//目标文件
File target = new File(targetPath);
//源根目录
String resourceAbsolutePath = resource.getAbsolutePath();
//目标根目录
String targetAbsolutePath = target.getAbsolutePath();
//目标目录不存在 创建目录
if (!target.exists()){
target.mkdirs();
}
//源目录下的文件
File[] resourceFiles = resource.listFiles();
//遍历根路径下所有元素
if (resourceFiles.length != 0){
for (int i = 0; i < resourceFiles.length; i++){
//当前文件的根路径
String absolutePath = resourceFiles[i].getAbsolutePath();
//当前文件的相对路径
String relativePath = absolutePath.substring(resourceAbsolutePath.length());
//拼接目标文件路径
String tempTargetPath = targetAbsolutePath + relativePath;
//是文件直接复制
if (resourceFiles[i].isFile()){
//复制文件
copyFile(absolutePath, tempTargetPath);
}else{
//文件夹
//文件夹下面没有文件
//创建文件夹
if(resourceFiles[i].listFiles().length ==0){
File targetFile = new File(tempTargetPath);
if (!targetFile.exists()){
targetFile.mkdirs();
}
}
//文件夹下有文件
//再次调用copy
copy(resourceFiles[i].getAbsolutePath(),tempTargetPath);
}
}
}
}
/**
* 复制文件
* @param resourceFilePath
* 源文件路径
* @param targetFilePath
* 目标文件路径
* @throws IOException
*/
public static void copyFile(String resourceFilePath, String targetFilePath) throws IOException {
FileInputStream fis = null;
FileOutputStream fos = null;
File targetFile = new File(targetFilePath);
File parentPath = new File(targetFile.getParent());
//文件父路径不存在创建文件路径
if (!parentPath.isDirectory()){
parentPath.mkdirs();
}
try {
fis = new FileInputStream(resourceFilePath);
fos = new FileOutputStream(targetFilePath);
int count = -1;
byte[] bytes = new byte[1024];
//读
while( (count = fis.read(bytes)) != -1){
//写
fos.write(bytes, 0, count);
}
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (fos != null) {
try {
fos.flush();
} catch (IOException e) {
throw new RuntimeException(e);
}
try {
fos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
JavaIO复制整个文件夹
最新推荐文章于 2024-07-22 14:15:06 发布