Java文件和文件夹的复制

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Java文件和文件夹的复制

浅尐墨〆   2022-06-28 我要评论

1、使用文件流对单个文件进行复制

将某个文件复制到指定的路径下:

//复制文件
public static void copy(File f1, String path) throws IOException {
        System.out.println("***copy***" + f1.getName());
        FileInputStream in = new FileInputStream(f1);
        FileOutputStream out = new FileOutputStream(path + f1.getName());
        byte[] bytes = new byte[512];
        while ((in.read(bytes)) != -1) {
            out.write(bytes, 0, bytes.length);
        }
        out.close();
        in.close();
    }

2、使用文件流将文件及文件夹下的文件进行复制

将a文件夹下的文件拷贝到b文件夹里。a和b文件夹可能存在相同文件,若b文件夹下已经存在a文件夹中的文件则不拷贝,若不存在则拷贝。

(1)递归复制文件夹下的文件

public static void copyAll(File A, File B) throws IOException {
        boolean flag = true;
        if (!B.exists()) {
            B.mkdir();
        }
        String[] a=A.list();
        //遍历A中所有文件及文件夹
        for (int i = 0; i < a.length; i++) {
            System.out.println("a:"+a[i]);
            //若A中含有文件夹
            if (new File(A.getPath()+"/"+a[i]).isDirectory()) {
                File newFolder=null;
                if (! ( new File(B.getPath()+"/"+a[i]).exists() )) {
                    newFolder = new File(B, a[i]);
                    newFolder.mkdir(); //创建子文件夹
                }
                //递归,判断
                copyAll(new File(A.getPath()+"/"+a[i]), newFolder);
            }
            //若A中含有文件,直接复制文件
            else {
                copyOtherFile(new File(A.getPath()+"/"+a[i]), B);
            }            
        }
        
    }

(2)若含有同名文件,则不进行复制

public static void copyOtherFile(File srcfile, File destfile) throws IOException {
        File[] destlist = destfile.listFiles();
        boolean flag = true;
            flag = true;
            for (File f2 : destlist) {
                System.out.println("f:" + srcfile.getName());
                System.out.println("f2:" + f2.getName());
                //含有同名文件,不进行复制
                if (srcfile.getName().equals(f2.getName())) {
                    System.out.println("相同");
                    flag = false;
                    break;
                } else {
                    System.out.println("不相同");
                }
            }
            if (flag) {
                copy(srcfile, destfile.getPath() + "/");
            }
        
    }

(3)主函数调用

public static void main(String[] args) throws IOException {
        File file = new File("F:/a");
        File file2 = new File("F:/b");
        copyAll(file, file2);
        System.out.println("复制成功!!!");
    }

下一篇:Java实现文件及文件夹的删除

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们