在Java中使用Files类的copy()方法复制文件的示例
在 Java 里,java.nio.file.Files
类的 copy()
方法可用于复制文件或目录。下面为你提供使用 copy()
方法复制文件的示例代码:
简单文件复制示例
以下代码将一个文件从源路径复制到目标路径。
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;public class FileCopyExample {public static void main(String[] args) {// 源文件路径String sourceFilePath = "path/to/source/file.txt";// 目标文件路径String targetFilePath = "path/to/target/file.txt";Path sourcePath = Paths.get(sourceFilePath);Path targetPath = Paths.get(targetFilePath);try {// 复制文件Files.copy(sourcePath, targetPath);System.out.println("文件复制成功");} catch (IOException e) {System.err.println("文件复制失败: " + e.getMessage());}}
}
代码解释:
1)指定路径:定义了源文件路径 sourceFilePath
和目标文件路径 targetFilePath
。
2)创建 Path
对象:利用 Paths.get()
方法依据文件路径创建 Path
对象。
3)复制文件:调用 Files.copy()
方法将源文件复制到目标路径。
4)异常处理:使用 try-catch
块捕获并处理可能出现的 IOException
异常。
覆盖已存在的目标文件
若目标文件已存在,Files.copy()
方法会抛出 FileAlreadyExistsException
异常。若你想覆盖已存在的目标文件,可使用 StandardCopyOption.REPLACE_EXISTING
选项。
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 FileCopyWithReplace {public static void main(String[] args) {String sourceFilePath = "path/to/source/file.txt";String targetFilePath = "path/to/target/file.txt";Path sourcePath = Paths.get(sourceFilePath);Path targetPath = Paths.get(targetFilePath);try {Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);System.out.println("文件复制成功(覆盖已存在文件)");} catch (IOException e) {System.err.println("文件复制失败: " + e.getMessage());}}
}
在这个示例中,StandardCopyOption.REPLACE_EXISTING
选项作为第三个参数传递给 Files.copy()
方法,这表明如果目标文件已存在,会对其进行覆盖。
你需要把 "path/to/source/file.txt"
和 "path/to/target/file.txt"
替换为实际的文件路径。