Spring Boot ClassPathResource读取文件方法详解,解决找不到资源问题?
更新时间:2026年07月13日 17:22:50 作者:sayyy
还在为Spring Boot读取classpath文件发愁吗?本文深入解析ClassPathResource的构造器用法和类加载器选择,通过实例演示如何正确读取资源,并帮你避开找不到文件的常见陷阱,让你的资源加载更稳健
前言
- java 1.8
- springboot 2.5.4
ClassPathResource读取文件
ClassPathResource 表示从类路径获取资源,它使用线程上下文类加载器、给定的类加载器来加载资源。classpath 资源存在于类路径中的文件系统中或 jar 包里。
ClassPathResource 常用构造器
public ClassPathResource(String path); public ClassPathResource(String path, @Nullable ClassLoader classLoader); public ClassPathResource(String path, @Nullable Class<?> clazz);
- public ClassPathResource(String path):使用默认的类加载器记载 path 类路径下的资源
- public ClassPathResource(String path, @Nullable ClassLoader classLoader):使用指定的类加载器加载 path 类路径下的资源
- public ClassPathResource(String path, @Nullable Class clazz):只用指定的类加载 path 类路径下的资源
示例1:读取 classpath 中的文件(1.txt)
@SpringBootApplication
public class Demo1Application {
public static void main(String[] args) {
SpringApplication.run(Demo1Application.class, args);
}
@Bean
public CommandLineRunner checkImage() {
return (args)->{
ClassPathResource cpr = new ClassPathResource("1.txt");
System.out.println("1.txt is exists : " + cpr.getFile().exists());
};
}
}
项目目录结构
项目 ├─src │ ├─main │ │ ├─java │ │ │ └─com │ │ │ └─example │ │ │ └─demo │ │ │ └─Demo1Application.java │ │ └─resources │ │ ├─application.properties │ │ └─1.txt │ └─test └─pom.xml
执行结果
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.5.4) 2021-08-31 23:02:31.892 INFO 109456 --- [ main] com.example.demo.Demo1Application : Starting Demo1Application using Java 1.8.0_144 on LAPTOP-F1O81IBU with PID 109456 (D:\sde\eclipse-workspace\demo-1\target\classes started by lhg in D:\sde\eclipse-workspace\demo-1) 2021-08-31 23:02:31.895 INFO 109456 --- [ main] com.example.demo.Demo1Application : No active profile set, falling back to default profiles: default 2021-08-31 23:02:32.265 INFO 109456 --- [ main] com.example.demo.Demo1Application : Started Demo1Application in 0.635 seconds (JVM running for 1.554) 1.txt is exists : true
示例2:找不到文件
代码与示例1一样。改变1.txt的位置(将文件移动到项目根目录)后,执行结果为:
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.5.4) 2021-08-31 22:54:57.996 INFO 113616 --- [ main] com.example.demo.Demo1Application : Starting Demo1Application using Java 1.8.0_144 on LAPTOP-F1O81IBU with PID 113616 (D:\sde\eclipse-workspace\demo-1\target\classes started by lhg in D:\sde\eclipse-workspace\demo-1) 2021-08-31 22:54:57.997 INFO 113616 --- [ main] com.example.demo.Demo1Application : No active profile set, falling back to default profiles: default 2021-08-31 22:54:58.372 INFO 113616 --- [ main] com.example.demo.Demo1Application : Started Demo1Application in 0.616 seconds (JVM running for 1.517) 2021-08-31 22:54:58.375 INFO 113616 --- [ main] ConditionEvaluationReportLoggingListener : Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled. 2021-08-31 22:54:58.391 ERROR 113616 --- [ main] o.s.boot.SpringApplication : Application run failed java.lang.IllegalStateException: Failed to execute CommandLineRunner at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:794) [spring-boot-2.5.4.jar:2.5.4] at org.springframework.boot.SpringApplication.callRunners(SpringApplication.java:775) [spring-boot-2.5.4.jar:2.5.4] at org.springframework.boot.SpringApplication.run(SpringApplication.java:345) [spring-boot-2.5.4.jar:2.5.4] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) [spring-boot-2.5.4.jar:2.5.4] at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) [spring-boot-2.5.4.jar:2.5.4] at com.example.demo.Demo1Application.main(Demo1Application.java:13) [classes/:na] Caused by: java.io.FileNotFoundException: class path resource [1.txt] cannot be resolved to URL because it does not exist at org.springframework.core.io.ClassPathResource.getURL(ClassPathResource.java:202) ~[spring-core-5.3.9.jar:5.3.9] at org.springframework.core.io.AbstractFileResolvingResource.getFile(AbstractFileResolvingResource.java:150) ~[spring-core-5.3.9.jar:5.3.9] at com.example.demo.Demo1Application.lambda$0(Demo1Application.java:20) [classes/:na] at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:791) [spring-boot-2.5.4.jar:2.5.4] ... 5 common frames omitted
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
java中@JsonValue和@JsonCreator使用
本文主要介绍了java中@JsonValue和@JsonCreator使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2024-06-06
Java中的InputStreamReader和OutputStreamWriter源码分析_动力节点Java学院整理
本文通过示例代码给大家解析了Java中的InputStreamReader和OutputStreamWriter知识,需要的的朋友参考下吧2017-05-05


最新评论