复制单级,多级文件夹
/*A:案例演示: 需求: 复制C:\\Users\\l\\Desktop\\aaa这文件夹到D:\\aaa
- 分析:
- a: 封装C:\\Users\\l\\Desktop\\aaa为一个File对象
- b: 封装D:\\aaa为一个File对象,然后判断是否存在,如果不存在就是创建一个目录
- c: 获取a中的File对应的路径下所有的文件对应的File数组
- d: 遍历数组,获取每一个元素,进行复制
- e: 释放资源*/
public class Demo6 {
public static void main(String[] args) throws IOException {
File srcFolder = new File("C:\\Users\\l\\Desktop\\aaa");
File destFolder = new File("D:\\aaa");
if (!destFolder.exists()) {
destFolder.mkdirs();
}
File[] files = srcFolder.listFiles();
for (File file : files) {
String name = file.getName();
File newFile = new File(destFolder, name);
copyFile(file,newFile);
}
}
private static void copyFile(File file,File newFile) throws IOException {
FileInputStream in = new FileInputStream(file);
FileOutputStream out = new FileOutputStream(newFile);
byte[] bytes = new byte[1024];
int len=0;
while ((len=in.read(bytes))!=-1){
out.write(bytes,0,len);
out.flush();
}
in.close();
out.close();
}
}
复制多级文件夹
/*A:案例演示: 需求: 复制C:\\Users\\l\\Desktop\\aaa这文件夹到D:\\aaa
- 分析:
- a: 封装C:\\Users\\l\\Desktop\\aaa为一个File对象
- b: 封装D:\\aaa为一个File对象,然后判断是否存在,如果不存在就是创建一个目录
- c: 获取a中的File对应的路径下所有的文件对应的File数组
- d: 遍历数组,获取每一个元素,
如果这个元素是文件就进行复制
如果是文件夹,就进行递归
- e: 释放资源*/
public class Demo7 {
public static void main(String[] args) throws IOException {
File srcFolder = new File("C:\\Users\\l\\Desktop\\aaa");
File destFolder = new File("D:\\aaa");
copyFolder(srcFolder, destFolder);
}
private static void copyFolder(File srcFolder, File destFolder) throws IOException {
if (srcFolder.isDirectory()){
String name = srcFolder.getName();
File newFile = new File(destFolder, name);
if (!newFile.exists()){
newFile.mkdirs();
}
File[] files = srcFolder.listFiles();
for (File file : files) {
//采用递归
copyFolder(file,newFile);
}
}else{
File newFile = new File(destFolder, srcFolder.getName());
copyFile(srcFolder,newFile);
}
}
private static void copyFile (File srcFolder, File newFile) throws IOException {
FileInputStream in = new FileInputStream(srcFolder);
FileOutputStream out = new FileOutputStream(newFile);
byte[] bytes = new byte[1024];
int len = 0;
while ((len = in.read(bytes)) != -1) {
out.write(bytes, 0, len);
out.flush();
}
in.close();
out.close();
}
}