在 Java 的 Spring Boot 项目中,可以使用以下代码将 resource 目录下的文件写入到 Windows 或 Linux 系统的指定路径:

import org.apache.commons.io.FileUtils;
import org.springframework.core.io.ClassPathResource;

import java.io.File;
import java.io.IOException;

public class FileCopyExample {

    public static void main(String[] args) {
        copyFileFromResourceToPath('file.txt', 'C:\temp\file.txt');
        //copyFileFromResourceToPath('file.txt', '/home/user/file.txt');
    }

    public static void copyFileFromResourceToPath(String resourceName, String destinationPath) {
        try {
            // 从类路径加载资源文件
            ClassPathResource resource = new ClassPathResource(resourceName);

            // 获取资源文件对象
            File file = resource.getFile();

            // 将文件复制到目标路径
            FileUtils.copyFile(file, new File(destinationPath));

            System.out.println('File copied successfully!');
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

以上代码使用了 Apache Commons IO 库的 FileUtils.copyFile() 方法,该方法用于将文件从一个路径复制到另一个路径。在代码中,我们首先使用 ClassPathResource 类加载 resource 目录下的文件,然后通过 getFile() 方法获取文件对象,最后通过 copyFile() 方法将文件复制到目标路径。请根据需要自行替换文件名和目标路径。

Spring Boot 项目文件写入 Windows 和 Linux 路径

原文地址: https://www.cveoy.top/t/topic/bnqh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录