Java实现文件的复制小案例

540 阅读1分钟

我坚信:talk is cheap, show me the code.

  • 话不多说,直接上代码:
public class CopyFileTest {
    public static void main(String[] args) throws IOException {
        // 需要拷贝的文件
        File f_1 = new File("D:\\IDEA_DarkHorse\\JavaJob\\MyTest\\src\\com\\leboy1\\aaa");
        // 要拷贝到的目录
        File f_2 = new File("D:\\IDEA_DarkHorse\\JavaJob\\job_day15\\src\\com\\leboy\\exer3");
        copyFile(f_1,f_2);
    }
    private static void copyFile(File from,File to) throws IOException {
        // 需要拷贝的文件->文件及文件夹数组
        File[] files = from.listFiles();
        File f_to = new File(to, from.getName());
        f_to.mkdir();
        //空文件夹直接省事儿
        if (files.length == 0 ){
            return;
        }
        // 所有的东西开始装
        to = f_to;
        for (File f : files) {
            if (f.isDirectory()){
                File dic = new File(to, f.getName());
                dic.mkdir();
                copyFile(f,dic);
            }else {
                // 定义每次传输的大小
                byte[] bytes = new byte[1024];
                // 读取有效的长度
                int len = 0 ;
                FileInputStream f_in = new FileInputStream(f);
                FileOutputStream f_out = new FileOutputStream(new File(to, f.getName()));
                while ((len = f_in.read(bytes))!=-1){
                    f_out.write(bytes,0 ,len );
                }
                f_out.close();
                f_in.close();
            }
        }
    }
}