本文是一个范例 : 文件夹的拷贝
package example;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* 文件夹的拷贝.
*/
public class TestDemo {
public static void main(String[] args) {
String srcPath = "E:\\test";
String destPath = "E:\\my";
try {
copyDirectory(srcPath, destPath);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 文件夹拷贝方法的重载
* @param srcPath
* @param destPath
* @throws Exception
*/
public static void copyDirectory(String srcPath,String destPath) throws Exception{
File src = new File(srcPath);
File dest = new File(destPath);
if(src.isDirectory()) {
dest = new File(destPath,src.getName());
dest.mkdirs();
}
copyDirectory(src,dest);
}
/**
* 用递归实现文件夹的拷贝
* @param srcFile
* @param destFile
* @throws Exception
*/
public static void copyDirectory(File srcFile,File destFile) throws Exception{
if(srcFile.isFile()){
File dest = new File(destFile,srcFile.getName());
copyFile(srcFile, dest);
}
if(srcFile.isDirectory()){
for(File f : srcFile.listFiles()) {
if(f.isFile()) {
File dest = new File(destFile,f.getName());
copyFile(f, dest);
}
if(f.isDirectory()) {
File dest = new File(destFile,f.getName());
dest.mkdirs();
copyDirectory(f,dest);
}
}
}
}
/**
* 拷贝文件
* @param src : 拷贝的源文件File对象
* @param dest : 拷贝的目标文件File对象
* @throws Exception
*/
public static void copyFile(File src, File dest) throws Exception {
if(!src.isFile()){
throw new IOException("只有文件才能拷贝.");
}
if(!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
if (src.exists()) {
InputStream input = new FileInputStream(src);
OutputStream output = new FileOutputStream(dest);
int len = 0;
byte data[] = new byte[1024];
while ((len = input.read(data)) != -1) {
output.write(data, 0, len);
}
output.close();
input.close();
}
}
/**
* 拷贝文件
* @param srcPath : 拷贝的源文件路径
* @param destPath : 拷贝的目标文件路径
* @throws Exception
*/
public static void copyFile(String srcPath, String destPath)
throws Exception {
copyFile(new File(srcPath), new File(destPath));
}
}