天天看点

java递归复制文件夹代码示范

package 递归复制文件夹;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

/* 递归复制文件
 *
 * 思路:递归每一个文件夹,访问其内部
 * 		如果当前是文件,则复制到相应的路径
 * 		如果当前是文件夹,则在相应的路径创建一个新的文件夹
 */

public class FileOutputStreamTest {
    public static String FROMPATH = "D:\\A星算法";// 填写【源文件夹】的绝对路径
    public static String TOPATH =   "D:\\day04";// 填写【目标文件夹】的绝对路径(若不存在,自动创建)

    public static void main(String[] args) {
        printFile(new File(FROMPATH));
    }

    // 递归函数
    public static void printFile(File f) {
        // 复制
        String newpath = TOPATH + f.getPath().substring(TOPATH.length() - 1, f.getPath().length());
        File tempf = new File(newpath);
        if (f.isDirectory()) {// 文件夹
            if (!tempf.exists()) {
                tempf.mkdirs();
            }
        }

        // 递归其内部
        if (f.isDirectory()) {
            File[] files = f.listFiles();
            for (File temp : files) {
                printFile(temp);
            }
        }else {// 文件
            System.out.println("复制文件:"+f.getPath()+"到"+newpath);
            copy(f.getPath(), newpath);
        }
    }

    // 复制文件
    public static void copy(String from, String to) {
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try {
        	fis = new FileInputStream(from);
        	fos = new FileOutputStream(to);
            byte[] bbuf = new byte[32];
            int len= 0;
            // 循环从输入流中取出数据
            while ((len = fis.read(bbuf)) !=-1) {
                // 读多少,写多少
                fos.write(bbuf, 0, len);
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }finally {
			try {
				if (fis!=null){
					fis.close();
					fis=null;
				}
			}catch (Exception e){
				e.printStackTrace();
			}finally {
			    try {
                    if (fos!=null){
                        fos.close();
                        fos=null;
                    }
                }catch (Exception e){
			        e.printStackTrace();
                }
            }
		}
    }
}