Java

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

小亿
196
2024-03-19 16:54:48
栏目: 编程语言

在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方法用于解析文件名并拼接到目标目录的路径中。最后输出文件拷贝成功的提示信息。

0
看了该问题的人还看了