Java 多文件夹合并
来源:互联网 发布:网络稳定性测试软件app 编辑:程序博客网 时间:2024/06/05 20:46
出处:点击打开链接
- 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 {
-
-
-
-
- public static void main(String[] args) {
-
-
- String[] sourceDirNames = {"D:/LuceneEx","D:/LuceneEx2"};
- String targetDirName = "D:/LuceneEx_backup";
-
- combineDirectory(sourceDirNames,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("合并所有的文件夹完成...");
- }
-
-
-
-
-
-
- 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());
- }
-
-
-
-
-
-
- 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();
- }
- }
- }
- }