最近项目中需要拷贝某个目录及其下面的所有子文件,包括子文件夹。
思路:遍历某个目录下的所有文件,如果为文件,则直接拷贝;如果为文件夹,则递归遍历。
package com.xx.test.copy;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
public class TestCopyDir {
/**
* @param args
*/
public static void main(String[] args) {
String sourceDirName = "D:/LuceneEx";
String targetDirName = "D:/LuceneEx_backup";
copyDir(sourceDirName,targetDirName);
}
/**
* 拷贝目录,递归的方法
* @param sourceDirName
* @param targetDirName
*/
public static void copyDir(String sourceDirName, String targetDirName) {
File sourceDir = new File(sourceDirName);
File targetDir = new File(targetDirName);
if(sourceDir==null || !sourceDir.exists()){
throw new RuntimeException("待拷贝的文件夹不存在..."+sourceDir.getAbsolutePath());
}
if(!sourceDir.isDirectory()){
throw new RuntimeException("待拷贝的文件不是目录..."+sourceDir.getAbsolutePath());
}
if(!targetDir.exists()){
targetDir.mkdirs();
}
File[] files = sourceDir.listFiles();
for(int i=0;files!=null && i<files.length;i++){
if(files[i].isFile()){ //复制文件
copyFile(files[i],new File(targetDirName+File.separator+files[i].getName()));
}else if(files[i].isDirectory()){ //复制目录,递归的方法
// 复制目录
String dir1 = sourceDirName+File.separator+files[i].getName();
String dir2 = targetDirName+File.separator+files[i].getName();
copyDir(dir1, dir2);
}
}
}
/**
* 拷贝单个的文件
* @param sourceFile 源文件
* @param targetFile 目标文件
*/
private static void copyFile(File sourceFile, File targetFile) {
FileInputStream in = null;
BufferedInputStream bis = null;
FileOutputStream out = null;
BufferedOutputStream bos = null;
try {
// 新建文件输入流并对它进行缓冲
in = new FileInputStream(sourceFile);
bis = new BufferedInputStream(in);
// 新建文件输出流并对它进行缓冲
out = new FileOutputStream(targetFile);
bos = new BufferedOutputStream(out);
// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len =bis.read(b)) != -1) {
bos.write(b, 0, len);
}
// 刷新此缓冲的输出流
bos.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
if(bos!=null)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if(bis!=null)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}