温馨提示×

java怎么拷贝文件到另一个目录下

小亿
250
2024-06-03 14:30:10
栏目: 编程语言

在Java中,可以使用Files.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 targetDirectoryPath = "path/to/target/directory";

        try {
            Path sourcePath = Paths.get(sourceFilePath);
            Path targetDirectory = Paths.get(targetDirectoryPath);

            Files.copy(sourcePath, targetDirectory.resolve(sourcePath.getFileName()));
            System.out.println("File copied successfully.");
        } catch (IOException e) {
            System.err.println("An error occurred during file copy: " + e.getMessage());
        }
    }
}

在上面的代码中,首先指定源文件路径和目标目录路径,然后使用Paths.get方法获取Path对象,最后调用Files.copy方法将源文件拷贝到目标目录下。最后会输出"File copied successfully."表示文件拷贝成功。如果文件拷贝过程中发生错误,会捕获IOException并输出错误信息。

0