Spring Boot 项目将资源文件写入系统路径
在 Spring Boot 项目中,可以使用'ResourceLoader'来加载资源文件,并使用'FileUtils'将资源文件写入到系统路径。
首先,注入'ResourceLoader'实例,可以通过构造函数注入或者通过'@Autowired'注解注入。
@Autowired
private ResourceLoader resourceLoader;
然后,使用'resourceLoader'加载资源文件,将其转换为'File'对象,并将其写入到系统路径。
Resource resource = resourceLoader.getResource('classpath:your-resource-file.txt');
File file = resource.getFile();
// 指定系统路径
String systemPath = '/path/to/your-system-path/your-resource-file.txt';
FileUtils.copyFile(file, new File(systemPath));
需要注意的是,'resource.getFile()'方法只能用于加载本地文件系统中的资源文件,如果资源文件位于jar包中或者其他非本地文件系统路径,则需要使用其他方法进行处理。
另外,需要确保系统路径存在,并且具有写入权限。如果系统路径不存在,可以使用'FileUtils.forceMkdirParent(new File(systemPath))'方法创建路径。
String systemPath = '/path/to/your-system-path/your-resource-file.txt';
FileUtils.forceMkdirParent(new File(systemPath));
FileUtils.copyFile(file, new File(systemPath));
以上代码将会把'resource'下的'your-resource-file.txt'文件写入到系统路径'/path/to/your-system-path/your-resource-file.txt'中。
原文地址: https://www.cveoy.top/t/topic/bnt9 著作权归作者所有。请勿转载和采集!