用递归实现文件夹拷贝以及文件拷贝

别说谁变了你拦得住时间么 提交于 2020-01-10 23:35:13

异常部门我是直接处理的,如果嫌麻烦的话也可向外抛出

闲话不多说,直接上代码。。。


package com.ListFile;

import java.io.*;

/**
 * 统计文件个数
 */
public class CopyFile {

    //定义一个外部变量,用于存放拷贝文件时穿件新的文件夹名称
    
    public static String newFileName;
  	public static String address = "D";//定义拷贝地址的盘符

  /**
 	* main方法
   * @param args
   */
public static void main(String[] args) {
    File file = new File("F:/test");    //传入想拷贝的文件的路径
    count(file);
}

/**
 * 递归实现拷贝
 * @param file
 */
public static void  count(File file){
    if (null != file && file.exists()) {//递归头
        //递归体
        if (file.isFile()) {//如果是文件,直接拷贝
            copy(file.getAbsolutePath(),newFileName);
        }else{
            for (File   f :  file.listFiles()){//如果是文件夹,在目标地址穿件新的文件夹
               //构建新文件地址目录
                String pathinname = f.getAbsolutePath();
                String[] split = pathinname.split(":");
                String s = split[0];
                newFileName = pathinname.replaceFirst(s,address);
                File newFile = new File(newFileName);

                if (!newFile.exists()) {//判断这个新文件夹是否存在
                    if (f.isDirectory()){//如果源文件文件夹,则穿件新文件夹
                        //这里一定要用mkdirs() 不能用mkdir 不然创建路径时会抛异常
                        newFile.mkdirs();
                    }
                    if (f.isFile()){//如果源文件是文件,直接创建一个目标文件
                        try {
                            newFile.createNewFile();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                count(f);//递归调用
            }
        }
    }
}

/**
 * 拷贝文件
 * @param in
 * @param out
 */
public  static  void  copy(String in,String out){
    File fileIn = new File(in);//输入源
    File fileOut = new File(out);//输出源
    InputStream is= null;
    OutputStream os  = null;
    try {
        is = new FileInputStream(fileIn);
        os = new FileOutputStream(fileOut);
        byte[] flash = new byte[1024];
        int len = -1;
        while ((len = is.read(flash))!=-1){
            os.write(flash,0,len);
        }
        os.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
     	    }
  	   	  }
	  }
   }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!