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中有相关的文件

posted @ 2020-03-01 16:20  huahuayu  阅读(2004)  评论(0编辑  收藏  举报