package com.qiang.IO5;
import java.io.*;
public class FileCopy {
public static void main(String[] args) {
File source = new File("D:/projects/aa");
File target = new File("D:/Ideal wrok space/tt");
copy(source,target);
}
public static void copy(File source,File target){
if (!source.exists()){ //判断源文件路径是否存在
return;
}
if (source.isFile()){
//组合一个新的目标文件绝对路径
File newFilePath = new File(target,source.getName());
target.mkdirs(); //创建新的目标文件需要所有的父级别目录
copyFile(source,newFilePath);
return;
}
File[] files = source.listFiles();
for (File f: files
) {
//组合一个新的目标路径,使用原有的目标路径追加一个当前source文件加名字
File newTargetPath = new File(target,source.getName());
copy(f,newTargetPath);
}
//如果成行没有进入循环直接执行到这里表示当前的source所指向的路径是一个空文件夹,那么需要在目标位置创建这个文件夹
File newTargetPath = new File(target,source.getName());
newTargetPath.mkdirs();
}
private static void copyFile(File sourcePath, File targetPath){
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(sourcePath);
fileOutputStream = new FileOutputStream(targetPath);
byte[] bytes = new byte[1024];
int len = 0;
while ((len= fileInputStream.read(bytes))>=0){
fileOutputStream.write(bytes, 0,len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream!= null){
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fileOutputStream != null){
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
IO流之文件的复制
最新推荐文章于 2024-01-08 22:26:03 发布