用Java程序实现文件夹及其子文件拷贝的小例子
package com.hugo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class Copy {
//设置成静态常量,方便方法中调用
static String from = null;
static String to = null;
public static void main(String[] args) {
from = "h:\\a";
to = "f:\\b";
new Copy(from);
}
// 实现文件夹及文件的拷贝
public Copy(String str) {
File file = new File(str);
File[] files = file.listFiles();
for (File f : files) {
String a = f.getAbsolutePath();
if (f.isDirectory()) {
new Copy(a);// 再次判断是否为文件,递归
} else {
File b = new File(a.replace(from, to));// 路径转换,例,d:/a/b/c.txt 把from(d:/a)换成to(e:/b)-->e:/b/b/c.txt
File c = new File(b.getParent());// 获得目标文件的路径
c.mkdirs();// 创建目标文件路径的文件夹
copyFile(f, b);// 调用文件拷贝
}
}
}
// 文件的拷贝(文件源,目标文件)
public void copyFile(File src, File des) {
FileInputStream reader = null;
FileOutputStream out = null;
try {
reader = new FileInputStream(src);
out = new FileOutputStream(des);
byte[] bs = new byte[1024 * 1024 * 10];//10兆的字节数组
int i = 0;
try {
while ((i = reader.read(bs)) != -1) {
out.write(bs, 0, i);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {// 注意关闭流
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}