Java 将目录下所有文件移至/复制到另一目录

注意:File.renameTo方法有一定的局限性

Many aspects of the behavior of this method are inherently
* platform-dependent: The rename operation might not be able to move a
* file from one filesystem to another, it might not be atomic, and it
* might not succeed if a file with the destination abstract pathname
* already exists.  The return value should always be checked to make sure
* that the rename operation was successful.

重命名操作不能从一个文件系统移动到另一个文件系统,文件已经存在,则操作失败,返回false。所以要通过监控返回值,检查操作是否成功。

public boolean moveFiles(String oldPath, String newPath){
        boolean result = true;
        String[] filePaths = new File(oldPath).list();

        if (filePaths != null && filePaths.length > 0){
            if (!new File(newPath).exists()){
                if(!new File(newPath).mkdirs()){
                    System.out.println("文件夹创建失败");
                    return false;
                }
            }

            try{
                for (String filePath : filePaths) {
                    if (new File(oldPath + File.separator + filePath).isDirectory()){
                        moveFiles(oldPath + File.separator + filePath, newPath + File.separator + filePath);
                    }else if (new File(oldPath + File.separator + filePath).isFile()){
                        //复制文件到另一个目录
                        copyFile(oldPath + File.separator + filePath, newPath + File.separator + filePath);
                        //移动文件至另一个目录
                        if(!new File(oldPath + File.separator + filePath).renameTo(new File(newPath + File.separator + filePath))){
                            System.out.println(oldPath + File.separator + filePath +"文件复制失败");
                            result = false;
                            break;
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }

        return result;
    }

    public void copyFile(String oldPath, String newPath) throws IOException {
        File oldFile = new File(oldPath);
        File file = new File(newPath);
        FileInputStream in = new FileInputStream(oldFile);
        FileOutputStream out = new FileOutputStream(file);;

        byte[] buffer=new byte[2097152];

        while((in.read(buffer)) != -1){
            out.write(buffer);
        }
    }

 

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值