1. java 移动文件的方式有几种?
在 Java 中,可以使用多种方法来移动文件。
//使用 java.nio.file.Files 类的 move() 方法: import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; public class Main { public static void main(String[] args) throws Exception { Path source = Paths.get("/path/to/source/file.txt"); Path target = Paths.get("/path/to/target/file.txt"); Files.move(source, target); } } //使用 java.io.File 类的 renameTo() 方法: import java.io.File; //使用示例 public class Main { public static void main(String[] args) { File source = new File("/path/to/source/file.txt"); File target = new File("/path/to/target/file.txt"); source.renameTo(target); } } //完整工具类方法封装 /** * 文件移动 * 源文件不存在renameTo方法返回false但不会报错,所以在工具方法中加入主动检查源文件逻辑; * 目标文件如果存在,会被默认覆盖; * * @param oldPath 文件全路径 * @param newPath */ public static boolean renameFileTo(String oldPath, String newPath) { Log.d(TAG, "renameFileTo: oldPath=" + oldPath + " newPath=" + newPath); File source = new File(oldPath); if (!source.exists()) { Log.d(TAG, "renameFileTo: Source file not exits!"); return false; } File target = new File(newPath); File targetPatenFile = target.getParentFile(); if (!targetPatenFile.exists()) { boolean mkdirResult = targetPatenFile.mkdirs(); Log.d(TAG, "renameFileTo: Target parent file not exits! targetPatenFile=" + targetPatenFile); Log.d(TAG, "renameFileTo: Target parent file mkdir! mkdirResult=" + mkdirResult); } boolean result = source.renameTo(target); Log.d(TAG, "renameFileTo: result=" + result); return result; } //使用 Apache Commons IO 库的 FileUtils.moveFile() 方法: import org.apache.commons.io.FileUtils; public class Main { public static void main(String[] args) throws Exception { File source = new File("/path/to/source/file.txt"); File target = new File("/path/to/target/file.txt"); FileUtils.moveFile(source, target); } } //使用