首先明確環境是:希望讀取resources文件夾下的文件(該文件夾下的內容將會一同打包到jar包中)
其次明確一點:如果您希望獲取到文件名或者路徑,該文章並不能對你有所幫助。
問題發生:在使用ResoureUtils.getFile方法時,在IDE運行可以通過測試,當時當打成jar包後運行報java.io.FileNotFoundException
問題原因:猜測jvm並無法訪問jar包裏面的文件名和路徑,因爲文件存儲系統跟操作系統不同,但卻可以根據文件路徑和文件名來讀取文件裏面的內容
Resource[] resources;
resources = ResourcePatternUtils.getResourcePatternResolver(null).getResources("classpath:template");
String parentPath = resources[0].getFile().getParent(); //打成jar包後報錯
resources = ResourcePatternUtils.getResourcePatternResolver(null).getResources("classpath:template/**/*.vm");
for (Resource resource : resources) {
InputStream is = resource.getInputStream();
byte[] encoded = IOUtils.toByteArray(is);
String content = new String(encoded, Charset.forName("UTF-8"));
System.out.println(content); //可成功獲得文件裏面的內容
System.out.println(resource.getFilename()); //打成jar包後報錯
System.out.println(resource.getFile().getPath().replace(parentPath, ""));//打成jar包後報錯
}