import java.io.*;
import java.util.Scanner;
public class CopyFile {
public static void copyFolder(String resource, String target)throws Exception{
File resourceFile = new File(resource);
File targetFile = new File(target);
if(!targetFile.exists()){
targetFile.mkdirs();
}
File[] resourceFiles = resourceFile.listFiles();
for (File file : resourceFiles){
File file1 = new File(targetFile.getAbsolutePath() + File.separator + file.getName());
if(file.isFile()){
System.out.println("文件" + file.getName());
copyFile(file,file1);
}
if(file.isDirectory()){
String dir1 = file.getAbsolutePath();
String dir2 = file1.getAbsolutePath();
copyFolder(dir1,dir2);
}
}
}
public static void copyFile(File resouece, File target)throws Exception{
FileInputStream inputStream = new FileInputStream(resouece);
BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
FileOutputStream outputStream = new FileOutputStream(target);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outputStream);
byte[] bytes = new byte[1024*10];
int len = 0;
while ((len = inputStream.read(bytes))!= -1){
bufferedOutputStream.write(bytes, 0, len);
}
bufferedOutputStream.flush();
bufferedInputStream.close();
bufferedOutputStream.close();
inputStream.close();
outputStream.close();
}
public static void judgeType(String resource, String target) throws Exception {
File resourceJudge = new File(resource);
if(!resourceJudge.exists()){
throw new Exception("源路径:[" + resource + "]不存在");
}
if(!target.contains(":")){
target = resourceJudge.getParent() + File.separator + target;
}
File targetJudge = new File(target);
if(resourceJudge.isDirectory()){
if(targetJudge.isFile()){
System.out.println("源路径为文件夹,目标路径为文件,无法复制");
Scanner sc =new Scanner(System.in);
System.out.println("请重新输入源地址");
resource = sc.nextLine();
System.out.println("请重新输入目标地址");
target = sc.nextLine();
judgeType(resource,target);
}else {
copyFolder(resource,target);
}
}else {
if(targetJudge.isDirectory()){
target = target + File.separator + resourceJudge.getName();
targetJudge = new File(target);
copyFile(resourceJudge,targetJudge);
}else {
copyFile(resourceJudge,targetJudge);
}
}
}
public static void main(String[] args){
String resource,target;
Scanner sc =new Scanner(System.in);
System.out.println("请输入源地址");
resource = sc.nextLine();
System.out.println("请输入目标地址(在同一目录下复制只需要输入新的文件或文件夹名字)");
target = sc.nextLine();
try {
judgeType(resource,target);
}catch (Exception e){
e.printStackTrace();
}
}
}