利用File类和IO流将一个文件夹的所有内容拷贝到另一个文件夹下
程序员文章站
2022-06-16 13:42:39
...
class hello {
public static void main(String[] args) throws IOException {
File one = Dir();
File two = Dir();
if(one.equals(two)) {
System.out.println("目标文件是源文件夹的子文件夹");
}else {
Copy(one,two);
}
}
public static void Copy(File one , File two) throws IOException {
File toDir = new File(two,one.getName());//获取目标文件夹的目录
toDir.mkdir();//在目标文件夹目录下新建与源文件夹相同名字的文件夹
File[] files = one.listFiles();
for (File file : files) {
if(file.isFile()) {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(toDir,file.getName())));
int a;
if((a = bis.read()) != -1){
bos.write(a);
}
bis.close();
bos.close();
}else {
Copy(file, toDir);
}
}
}
public static File Dir() {//获取文件夹路径方法
System.out.println("请输入文件夹路径:");
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
File dir = new File(line);
while (true) {
if (!dir.exists()) {
System.out.println("路径不存在,请重新输入: ");
} else if (dir.isFile()) {
System.out.println("请重新输入一个文件夹路径");
} else {
return dir;
}
}
}
源文件夹:
运行结果:
复制后目标文件夹: