package CopyAllFile;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
System.out.print("请输入拷贝源目录:");
String srcPath=input.nextLine();
System.out.print("请输入目标目录:");
String destPath=input.nextLine();
//运行,找到原文件和获得目录拷贝文件
fileAndDirCopy(srcPath,destPath);//源文件和目标文件
}
//调用方法体
private static void fileAndDirCopy(String srcPath, String destPath) throws IOException {
//定义源文件,srcPath是源文件目录
File srcFile = new File(srcPath);
//File[] chilerenFiles=srcFile.listFiles((pathname)->pathname.isFile());
File[] chilerenFiles=srcFile.listFiles(new FileFilter() {
@Override
public boolean accept(File pathname) {
//判断是否文件;是返回true,
return pathname.isFile();
}
});
//定义目标文件
File destFile=new File(destPath);
if(!destFile.exists()){
//没有文件就补齐目录
destFile.mkdirs();
}
if (chilerenFiles!=null&&chilerenFiles.length>0) {
for(File file:chilerenFiles){
//遍历拷贝当前目录文件
fileCopy(file,destFile);
}
}
//判断是否为目录,是返回true,
递归方法出口
File[] childrenDirs=srcFile.listFiles((pathname)->pathname.isDirectory());
if(childrenDirs!=null&&childrenDirs.length>0){
}
private static void fileCopy(File srcFile, File destParentFile) throws IOException {
//定义入流
InputStream in = new FileInputStream(srcFile);
//定义出流
OutputStream out = new FileOutputStream(new File(destParentFile,srcFile.getName()));
//缓冲区
byte[] buffer = new byte[1024*1024*2];
int n = -1;
while (true) {
n=in.read(buffer);
if(n==-1){
break;
}
out.write(buffer, 0, n);;
out.flush();
}
out.close();
in.close();
}
}