You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Java Files.move方法移动文件时生成新file类型而非移动到指定目录问题

问题根因
  • Files.move()方法要求传入的目标路径是完整的目标文件路径,你当前只传入了目标目录路径G:\gohere:
    第一次移动文件时,系统会直接将源文件重命名为G:\gohere,覆盖掉你预先创建的目录,导致后续所有移动操作都失去了目标目录,自然无法正常执行。
  • 额外逻辑bug:当前代码仅遍历一级子目录,更深层级子文件夹内的MP4文件无法被扫描到;且根目录下的非MP4文件也会被强制移动,不符合你提取MP4的需求。
  • 异常捕获逻辑不完整:子目录内移动文件的catch块仅调用e.getMessage(),没有输出异常信息,无法快速定位问题。
修复后代码
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class MoveMp4 {
    static File dir = new File("G:\\New Folder");
    static Path targetDir = Paths.get("G:\\gohere");

    static void scanAndMove(File currentFile) {
        if (currentFile.isDirectory()) {
            File[] subFiles = currentFile.listFiles();
            if (subFiles == null) return;
            // 递归遍历所有层级子目录
            for (File sub : subFiles) {
                scanAndMove(sub);
            }
        } else {
            // 仅处理MP4文件
            if (currentFile.getName().endsWith(".mp4")) {
                Path sourcePath = currentFile.toPath();
                // 构造完整的目标文件路径:目标目录 + 源文件名
                Path targetPath = targetDir.resolve(sourcePath.getFileName());
                try {
                    // 目标目录不存在则先创建
                    if (!Files.exists(targetDir)) {
                        Files.createDirectories(targetDir);
                    }
                    // 移动文件,REPLACE_EXISTING参数可选,用于覆盖已存在的同名文件
                    Files.move(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
                    System.out.println("已移动文件:" + sourcePath);
                } catch (IOException e) {
                    System.out.println("移动文件失败:" + sourcePath);
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        scanAndMove(dir);
    }
}
核心修改点说明
  1. 改用递归遍历逻辑,支持扫描所有层级子目录下的MP4文件
  2. 增加MP4后缀判断统一逻辑,避免误移动其他格式文件
  3. 使用targetDir.resolve(sourcePath.getFileName())构造合法的目标文件路径,不会再覆盖目标目录
  4. 增加目标目录自动创建逻辑,避免目标目录不存在导致的移动失败
  5. 完善异常捕获逻辑,所有异常都会打印栈信息方便排查

如果你不需要覆盖已存在的同名文件,删除StandardCopyOption.REPLACE_EXISTING参数即可。

内容的提问来源于stack exchange,提问作者Why

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 11:30:03