【Spring】Resource接口:ClassPathResource

本文详细介绍了如何在Spring Boot应用中使用ClassPathResource读取classpath中的文件,并通过示例展示了正确操作和常见错误案例。重点讲解了三种构造器的使用以及类路径资源的定位原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

  • 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

参考

https://blog.csdn.net/qq_16830879/article/details/91876712

### SpringClassPathResource 的使用方法 #### 什么是 ClassPathResource? `ClassPathResource` 是 Spring 提供的一个工具类,主要用于加载位于类路径下的资源文件。它实现了 `Resource` 接口,并提供了多种方式来访问这些资源[^1]。 --- #### 创建 ClassPathResource 实例的方式 可以通过以下几种方式创建 `ClassPathResource` 对象: 1. **基于字符串路径** 如果资源路径是相对于类路径根目录,则可以直接传入路径字符串: ```java ClassPathResource resource = new ClassPathResource("config.properties"); ``` 2. **基于特定类的相对路径** 当资源文件位于某个具体类所在包下时,可以指定该类作为参数: ```java ClassPathResource resource = new ClassPathResource("resources/file.txt", MyClass.class); ``` 这里的 `"resources/file.txt"` 是相对于 `MyClass` 所在包的位置[^3]。 3. **通过线程上下文类加载器** 可以利用默认的线程上下文类加载器加载资源: ```java ClassPathResource resource = new ClassPathResource("data.json"); InputStream inputStream = resource.getInputStream(); ``` --- #### 常见操作示例 以下是几个常见的用法示例: ##### 示例 1:读取配置文件的内容 假设有一个名为 `application.properties` 的文件存储在类路径下,我们可以这样读取其内容: ```java import org.springframework.core.io.ClassPathResource; import java.io.BufferedReader; import java.io.InputStreamReader; public class ResourceExample { public static void main(String[] args) throws Exception { ClassPathResource resource = new ClassPathResource("application.properties"); try (BufferedReader reader = new BufferedReader(new InputStreamReader(resource.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } } } ``` 上述代码会逐行打印出 `application.properties` 文件中的每一行数据[^4]。 ##### 示例 2:将资源转换为字节数组 如果需要将整个资源文件加载到内存中作为一个字节数组,可按如下实现: ```java import org.springframework.core.io.ClassPathResource; import org.apache.commons.io.IOUtils; public class ByteArrayExample { public static void main(String[] args) throws Exception { ClassPathResource resource = new ClassPathResource("image.png"); byte[] bytes = IOUtils.toByteArray(resource.getInputStream()); // 处理字节数组... } } ``` ##### 示例 3:判断资源是否存在 有时我们需要先确认资源是否可用再执行后续逻辑: ```java import org.springframework.core.io.ClassPathResource; public class ExistenceCheck { public static void main(String[] args) { ClassPathResource resource = new ClassPathResource("missing-file.txt"); if (!resource.exists()) { System.out.println("The file does not exist."); } else { System.out.println("File found!"); } } } ``` --- #### 特殊场景支持 除了基本功能外,`ClassPathResource` 还能处理一些特殊需求,比如从 JAR 包内部加载资源或者跨模块项目结构中的资源共享问题[^2]。 例如,在打包后的应用程序中查找嵌套于 JAR 文件内的静态 HTML 页面或其他前端资产文件。 --- #### 总结 `ClassPathResource` 是一种简单而强大的机制,能够帮助开发者轻松定位并管理运行时所需的外部依赖项或辅助材料。无论是简单的属性文件还是复杂的多媒体素材,都可以借助这一 API 完成高效加载与解析工作[^5]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值