递归:
递归:
5,复制一个文件夹里面的所有内容到另外一个文件夹,包括里面的子文件夹
package com.studyjava.chapter5;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class Practice5 {
public static void main(String[] args) {
copyFilesWithsubFloder("D:\\dev\\test\\bw\\2\\", "D:\\dev\\test\\bw\\3\\");
}
public static void copyFilesWithsubFloder(String source, String target) {
File src = new File(source);
File dest = new File(target);
if (src.isDirectory()) {
for(File f: src.listFiles()) {
if(f.isFile())
copyFile(f, new File(target, f.getName()));//通过目标路径和文件名构造目标File文件对象,然后copy
else {
File newFloder = new File(target, f.getName());
if(!newFloder.exists())
newFloder.mkdir();//根据目标文件夹路径和源文件夹名称在目标文件夹路径建立文件夹
copyFilesWithsubFloder(f.getAbsolutePath(),newFloder.getAbsolutePath());//复制动作
}
}
}
else {
System.out.println("the source should be a floder.");
}
}
public static void copyFile(File src, File dest) {
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(src));
bos = new BufferedOutputStream(new FileOutputStream(dest));
byte[] bys = new byte[1024];
int length = -1;
while ((length = bis.read(bys))!=-1) {
bos.write(bys, 0, length);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
try {
if(bis!=null)
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if(bos!=null)
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}