java classPathResource FileNotFoundException解決辦法


原文鏈接:https://liushiming.cn/2020/02/26/java-classpathresource-filenotfoundexception/

概述

今天通過java程序讀取resource文件夾里面的一些文件,文件明明放到了指定的文件夾,通過classPathResource來讀取,但是程序報文件不存在。

讀文件的代碼:

ClassPathResource classPathResource = new ClassPathResource("foo.txt");
InputStream input = classPathResource.getInputStream();

錯誤信息:

java.io.FileNotFoundException: class path resource [foo.txt] cannot be opened because it does not exist

問題原因

文件只在源代碼中,不在target文件夾中,而classPathResource.getInputStream()是讀編譯后的文件,不是源代碼文件:

解決方案

rebuild project(也可以先把target刪了再rebuild),確保target中有相關的文件


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM