复制文件夹

/*
* 复制文件夹
*/
public static void main(String[] args) {
//想要复制的文件夹
File src = getDir();
//复制到那个文件夹
File dest = getDir();
copyDir(src, dest);
}

public static void copyDir(File dir, File dest) {
File newDir = new File(dest, dir.getName());
newDir.mkdir();
File[] subFiles = dir.listFiles();
for (File subFile : subFiles) {
if (subFile.isFile()) {
try {
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(subFile));
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream(new File(newDir,
subFile.getName())));
int len = 0;
while ((len = bis.read()) != -1) {
bos.write(len);
}
bos.close();
bis.close();
} catch (IOException e) {
e.printStackTrace();
}

} else {
copyDir(subFile, newDir);
}
}
}
public static File getDir() {
Scanner sc = new Scanner(System.in);
System.out.println("请输入文件夹路径:");
while (true) {
String pathname = sc.nextLine();
File dir = new File(pathname);
if (!dir.exists()) {
System.out.println("您输入的路径不存在,请重新输入.");
} else if (dir.isFile()) {
System.out.println("您输入的是一个文件路径,请输入一个文件夹路径.");
} else {
return dir;
}
}
}

你可能感兴趣的:(java)