package Test1_1;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* 需求:将一个文件夹下的所有文件复制到指定文件下
*
* @author thinkpad
*
*/
public class CopyFiles {
public static void main(String[] args) {
File src = new File("c:\\javaee");
File des = new File("c:\\Tools\\day11");
copyFiles(src, des);
}
/**
* 创建一个方法实现文件夹的复制
*
* @param src
* @param des
*
*/
public static void copyFiles(File src, File des) {
if (!src.exists())
throw new RuntimeException("找不到指定文件夹");
if((!des.isDirectory())||!des.exists())
des.mkdirs();
File[] files = src.listFiles();
for (File f : files) {
String name = f.getName();
File f1 = new File(des, name);
if (f.isDirectory()) {
//f1.mkdirs();
copyFiles(f, f1);
}
else{
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(f));
bos = new BufferedOutputStream(new FileOutputStream(f1));
int len = 0;
while ((len = bis.read()) != -1) {
bos.write(len);
}
} catch (IOException e) {
throw new RuntimeException("复制文件失败");
} finally {
if (bis != null)
try {
bis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (bos != null)
try {
bos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(f+"文件复制成功");
}
}
System.out.println(src+"文件夹复制成功");
}
}
|
|