原文鏈接: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中有相關的文件