java如何拷贝文件到另一个目录下

1485
2024/3/24 16:54:48
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Java中拷贝文件到另一个目录下可以使用File类的方法来实现。以下是一个示例代码:

import java.io.File;
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 sourceFile = "path/to/source/file.txt";
        String targetDir = "path/to/target/directory";

        try {
            File fileToCopy = new File(sourceFile);
            File targetDirectory = new File(targetDir);

            // 检查目标目录是否存在,如果不存在则创建
            if (!targetDirectory.exists()) {
                targetDirectory.mkdirs();
            }

            // 使用Files类的copy方法拷贝文件
            Path sourcePath = Paths.get(fileToCopy.toURI());
            Path targetPath = Paths.get(targetDirectory.toURI());
            Files.copy(sourcePath, targetPath.resolve(sourcePath.getFileName()));

            System.out.println("文件拷贝成功!");

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上面的示例中,首先指定了源文件和目标目录的路径,然后检查目标目录是否存在,如果不存在则创建。接着使用Files类的copy方法来拷贝文件,其中sourcePath是源文件的路径,targetPath是目标目录的路径,resolve方法用于解析文件名并拼接到目标目录的路径中。最后输出文件拷贝成功的提示信息。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: java replace和replaceall的区别是什么