出处:点击打开链接
- 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 TestCombineDirectory {
- /**
- * @param args
- */
- public static void main(String[] args) {
- String[] sourceDirNames = {"D:/LuceneEx","D:/LuceneEx2"};
- String targetDirName = "D:/LuceneEx_backup";
- combineDirectory(sourceDirNames,targetDirName);
- }
- /**
- * 合并多个文件夹到一个文件夹中
- * @param sourceDirNames
- * @param targetDirName
- */
- private static void combineDirectory(String[] sourceDirNames,String targetDirName) {
- if(sourceDirNames==null || sourceDirNames.length==0){
- throw new RuntimeException("待合并的文件夹不存在...");
- }
- for(int i=0;i<sourceDirNames.length;i++){
- copyDir(sourceDirNames[i], targetDirName);
- }
- System.out.println("合并所有的文件夹完成...");
- }
- /**
- * 拷贝目录,递归的方法
- * @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);
- }
- }
- System.out.println("拷贝文件夹成功..."+sourceDir.getAbsolutePath());
- }
- /**
- * 拷贝单个的文件
- * @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();
- }
- }
- }
- }