需求: 从键盘接受两个文件夹路径. 把其中一个文件夹中的内容拷贝到另一个文件夹
1.获取文件夹路径
2.把其中一个文件夹中的内容拷贝到另一个文件夹
以下为两个方法
/*
* 获取文件夹路径
* 1.返回值类型File
* 2.参数列表 无
*/
public static File getDir(){
System.out.println("请输入文件夹路径");
Scanner sc = new Scanner(System.in);
while(true){
File file = new File(sc.nextLine());
if(!file.exists()) {
System.out.println("该文件夹路径不存在!重新输入");
}else if(file.isFile()){
System.out.println("请输入文件夹路径");
}else{
return file;
}
}
}
/*
* 把其中一个文件夹中的内容拷贝到另一个文件夹
* 1.返回值类型 void
* 2.参数列表 File src, File dest
*/
public static void copy(File src, File dest) throws IOException {
//1.在目标文件夹中创建原文件夹
File newDir = new File(dest,src.getName());
newDir.mkdir();
//2.获取原文件夹中所有的文件和文件夹
File[] subFiles = src.listFiles();
//3.遍历数组
for (File file : subFiles) {
//4.如果是文件就用io流读写
if(file.isFile()){
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bout =
new BufferedOutputStream(new FileOutputStream(new File(newDir,file.getName())));
int len;
while((len = bin.read())!= -1){
bout.write(len);
}
bin.close();
bout.close();
}else{
//5.如果是文件夹就递归调用
copy(file, newDir);
}
}
}