通过io实现对文件夹的拷贝
思路分析
- 通过文件夹的路径创建File对象通过File对象的isDirectory()来判断是文件还是文件夹
- a. 是文件拷贝文件
- b. 是文件夹 递归调用拷贝文件夹
代码示例
import java.io.*;
import java.util.Scanner;
public class copyfile {
public static void main(String args[]) throws IOException {
//获取文件路径
Scanner scanner=new Scanner(System.in);
String path=scanner.nextLine();
//拷贝文件 拷贝后的文件名为 原名+path
copyfilder(new File(path),new File(path+"copy"));
}
private static void copyfilder(File s, File s1) throws IOException {
if (s.isDirectory()){
//如果是文件夹 创建文件夹
s1.mkdirs();
//获取文件夹下的所有的文件对象
File[] temp=s.listFiles();
//遍历它
for (File file1:temp){
//递归调用
copyfilder(file1,new File(s1,file1.getName()));
}
}else{
//是文件 创建文件
s1.createNewFile();
//拷贝文件
copydata(s.getAbsolutePath(),s1.getAbsolutePath());
}
}
//通过io拷贝文件
private static void copydata(String absolutePath, String absolutePath1) {
FileInputStream inputStream=null;
FileOutputStream outputStream= null;
try {
outputStream=new FileOutputStream(absolutePath1);
inputStream=new FileInputStream(absolutePath);
byte [] by=new byte[1024];
int an= 0;
an = inputStream.read(by,0,by.length);
while(an>0){
outputStream.write(by,0,an);
outputStream.flush();
an=inputStream.read(by,0,by.length);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭资源
try {
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}