public static void main(String[] args) throws IOException {
Scanner sc =new Scanner(System.in);
System.out.println("请输入要拷贝的文件夹路径:");
String line1 = sc.nextLine();
System.out.println("请输入 接受文件夹的路径:");
String line2 = sc.nextLine();
File file1 =new File(line1);
File file2=new File(line2);
//复制文件夹的功能
copyFolder(file1,file2);
}
private static void copyFolder(File file1, File file2) throws IOException {
//判断File1是文件夹还是文件
if(file1.isDirectory()){
//是文件,先在目的地创建文件夹
File newFolder =new File(file2,file1.getName());
newFolder.mkdir();
//获取该File对象下的所有或者文件夹File对象
File[] fileArray =file1.listFiles();
for (File file : fileArray) {
copyFolder(file,newFolder);
}
}else{
//文件
File file3 =new File(file2,file1.getName());
copyFile(file1,file3);
}
}
private static void copyFile(File file1, File file3) throws IOException {
BufferedInputStream bis =new BufferedInputStream(new FileInputStream(file1));
BufferedOutputStream bos =new BufferedOutputStream(new FileOutputStream(file3));
byte[] a =new byte[1024];
int b ;
while((b=bis.read(a))!=-1){
bos.write(a, 0, b);
}
bis.close();
bos.close();
} |