Java动态将文件复制到另一个路径并改名

 private static void copy(String url1, String url2) throws Exception {
//字节输入流,用来读取文件
        FileInputStream in = new FileInputStream(new File(url1));
//字节输出流,用来写文件
        FileOutputStream out = new FileOutputStream(new File(url2));
        byte[] buff = new byte[512];
        int n = 0;
        while ((n = in.read(buff)) != -1) {
            out.write(buff, 0, n);
        }
        out.flush();
        in.close();
        out.close();
        System.out.println("复制完成");
    }

首先封装一个复制的方法,然后我们下面需要获取到文件再问们本地的路径,以及需要修改成什么样的文件名

List<SysFileInfoVo> children = list.get(i).getChildren();
                        if(children.size()>0){
                            for (int j = 0; j < children.size(); j++) {
                                //文件名
                                String fileName = children.get(j).getFileName();
                                //获取文件在本地的地址
                                String filePath = FileUtils.appendFilePath(basedir, children.get(j).getPath().substring(8));
                                //为了不改变原来本地文件,再次复制到另一个地方并重命名
                                String copyPath = copDir+"\\"+fileName;
                                copy(filePath,copyPath);
                            }
                        }

copyDir是我将要复制文件到的地址,filePath是我本地文件的地址,fileName是文件名;

展示如下:

(1)原来本地文件的地址

(2)复制完成的地址及文件名


版权声明:本文为kdjfh原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。