[英]Classpath resource not resolving in spring boot
我正在使用Spring Boot,並且資源文件夾中有一個文件。 我正在使用數字海洋機,並且當我使用java -jar mywebapp.war運行應用程序時,無法從類路徑訪問文件。 我正在使用以下標准語法進行訪問:
File file = new ClassPathResource("mfile").getFile();
我收到錯誤消息,指出類路徑資源無法解析為絕對路徑。 我看到的問題是它正在顯示路徑! 標記如下:
/home/u/webapp/target/mywebapp.war!/WEB-INF/classess!/mfile
我在這里做錯了什么?
由於使用java -jar
運行它,因此應將其構建為JAR文件而不是WAR。
了解更多: https : //docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html
作為jar運行時,獲取文件不起作用。您應將其作為資源流獲取。
ClassLoader classLoader = getClass().getClassLoader();
InputStream inputStream = classLoader.getResourceAsStream("/file.xsd") ;
File file = File.createTempFile("file", ".xsd");
try {
FileUtils.copyInputStreamToFile(inputStream, file);
} finally {
IOUtils.closeQuietly(inputStream);
它會為您提供文件。 如果要求是作為文件獲取。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.