Java中如何实现将指定文件移动到目标文件夹的功能
Java实现文件直接移动到指定文件夹的解决方案
你当前采用的复制后删除的实现效率低、可靠性差,Java已经提供了原生的文件移动API,不需要自行实现复制逻辑,以下是具体实现方案:
推荐方案:Java 7及以上使用NIO的Files.move(最优解)
该方案优势:
- 底层调用操作系统原生移动能力,同磁盘分区下仅修改文件元数据,速度极快,无需复制文件内容
- 自动处理跨分区移动的场景,可靠性远高于自行实现的复制删除逻辑
- 支持配置覆盖已有文件、原子移动等特性
可复用的工具方法实现:
import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; /** * 将指定文件移动到目标文件夹 * @param sourceFile 要移动的源文件 * @param targetDir 目标文件夹 * @param newFileName 可选参数,移动后的新文件名,传null则保留原文件名 * @throws IOException 移动过程中出现的IO异常 */ public static void moveFileToTargetDir(File sourceFile, File targetDir, String newFileName) throws IOException { // 校验源文件是否合法 if (!sourceFile.exists() || !sourceFile.isFile()) { throw new IllegalArgumentException("源文件不存在或不是合法文件"); } // 目标文件夹不存在则自动创建 if (!targetDir.exists()) { targetDir.mkdirs(); } // 构造目标文件完整路径 String targetFileName = newFileName == null ? sourceFile.getName() : newFileName; File targetFile = new File(targetDir, targetFileName); // 执行移动操作,REPLACE_EXISTING参数表示目标文件存在时直接覆盖,不需要该特性可删除此参数 Files.move(sourceFile.toPath(), targetFile.toPath(), StandardCopyOption.REPLACE_EXISTING); }
调用示例:
public static void main(String[] args) { try { File sourceFile = new File("C:\\Users\\anar.memmedov\\Desktop\\test.txt"); File targetDir = new File("C:\\Users\\anar.memmedov\\Desktop\\ok"); // 移动后文件重命名为test3.txt moveFileToTargetDir(sourceFile, targetDir, "test3.txt"); System.out.println("文件移动成功"); } catch (Exception e) { e.printStackTrace(); } }
兼容旧版本Java方案:使用File.renameTo方法
注意事项:
renameTo方法返回boolean值,需要手动判断是否移动成功- 跨磁盘分区移动时大概率会失败,仅推荐同分区移动场景使用
代码实现:
public static boolean moveFileToTargetDirOld(File sourceFile, File targetDir, String newFileName) { if (!sourceFile.exists() || !sourceFile.isFile()) { return false; } if (!targetDir.exists()) { targetDir.mkdirs(); } String targetFileName = newFileName == null ? sourceFile.getName() : newFileName; File targetFile = new File(targetDir, targetFileName); // 执行移动操作 return sourceFile.renameTo(targetFile); }
内容的提问来源于stack exchange,提问作者iwritecomeinmymind
相关产品推荐
相关产品推荐

