package com.cast;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class CopyFilestoOthers {
public static void main(String[] args) throws IOException {
File src = getDir();
File dest = getDir();
if(dest.equals(src)){
System.out.println("目标文件是源文件子目录!");
}else{
copy(src,dest);
}
System.out.println("文件夹已经复制完成.");
}
public static File getDir(){
Scanner sc = new Scanner(System.in);
System.out.println("输入文件夹路径:");
while(true){
String line = sc.nextLine();
File dir = new File(line);
if(!dir.exists()){
System.out.println("文件夹不存在!重输");
}else if(dir.isFile()){
System.out.println("不是文件夹!重输:");
}else{
return dir;
}
}
}
public static void copy(File src,File dest) throws IOException{
File newDir = new File(dest,src.getName());
if (!newDir.exists()) {
newDir.mkdir();
}
File[] subFiles = src.listFiles();
for (File subFile : subFiles) {
if(subFile.isFile()){
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(subFile));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(newDir,subFile.getName())));
int len;
while((len = bis.read()) != -1){
bos.write(len);
}
bis.close();
bos.close();
}else{
copy(subFile,newDir);
}
}
}
}