How to load external files in Spring Boot?
In Spring Boot, loading external files can be achieved using the @Value annotation.
Firstly, set the path to the external file in the configuration file such as application.properties or application.yml.
file.path=/path/to/file.txt
Next, use the @Value annotation in the class that needs to load external files to retrieve the file path from the configuration file.
@Value("${file.path}")
private String filePath;
Lastly, utilize the File class in Java or another file operation class to read the content of external files.
File file = new File(filePath);
// 进行文件操作
Please note that if the path of the external file is relative, it is relative to the directory where the Spring Boot application is running. If the path of the external file is absolute, you can use the absolute path directly.
Additionally, one can also use Spring’s ResourceLoader to load the content of external files. Inject a ResourceLoader object into the class and then use its getResource method to load the external file.
@Autowired
private ResourceLoader resourceLoader;
public void loadFile() throws IOException {
Resource resource = resourceLoader.getResource("file:" + filePath);
InputStream inputStream = resource.getInputStream();
// 进行文件操作
}
This method can handle more complex external file loading requirements, such as loading files under the classpath or files from URL addresses.