關於java讀取resource下檔案,程式報錯不存在問題的解決
阿新 • • 發佈:2021-02-17
技術標籤:# java記錄
先排除路徑錯誤等低階錯誤。
一般讀取某檔案,比如在resource目錄下的ehcache資料夾中有ehcache-shiro.xml檔案,使用以下方式讀取
ResourceUtils.getInputStreamForPath(“classpath:ehcache/ehcache-shiro.xml”);
程式碼中要思考,classpath意義。簡明之意是,告訴程式到編譯後的路徑下去讀取檔案,這一點通過看原始碼可以理解。
如果出現了原本有檔案,但仍報錯不存在,可以從編譯後的路徑中,檢視resource下檔案是否全部被編譯到輸出路徑。
如果發現編譯資料路徑下並沒有resource包含檔案的存在,那麼問題就找到了。
以我專案為例,springboot及maven。
1、在pom檔案中,指定編譯資源。
<build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> <resources> <resource> <directory>/statics</directory> <excludes> <exclude>**/*.woff</exclude> <exclude>**/*.woff2</exclude> <exclude>**/*.ttf</exclude> <exclude>**/*.eot</exclude> <exclude>**/*.svg</exclude> </excludes> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.*</include> </includes> </resource> </resources> </build>
2、若仍有問題,嘗試將pom檔案中 <packaging>pom</packaging> 註釋掉。再次編譯檢視。