項目中有時候會存放一些文件到resources中车要,需要用的時候進行獲取。
import org.springframework.core.io.ClassPathResource;
/**
* 獲取resource下的文件流
* @param filePath
* @return
*/
public static InputStream getResourceInputStream(String filePath) {
? ? try {
? ? ? ? ClassPathResource classPathResource = new ClassPathResource(filePath);
? ? ? ? // classPathResource.getFile() jar包的時候也不可用崭倘,會遇到URI is not hierarchical問題
? ? ? ? return classPathResource.getInputStream();
? ? } catch (Exception e) {
? ? ? ? log.error("獲取Resource中的文件異常 {} {}", filePath, e);
? ? }
}
例:
我們在resources中新建了一個test文件夾翼岁,在這個文件中放了一個test.txt文件。
那么我們通過下面的方法就能獲取到文件流:getResourceInputStream("test/test.txt")
不需要在maven中做額外的配置司光。
使用jar包的時候琅坡,不能使用getFile方法,會碰到URI is not hierarchical問題残家。
可以用getInputStream方法榆俺,獲取到stream,而后進行根據(jù)自身的需求進行轉(zhuǎn)化