java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Spring Boot ClassPathResource读取文件方法

Spring Boot ClassPathResource读取文件方法详解,解决找不到资源问题?

作者:sayyy

还在为Spring Boot读取classpath文件发愁吗?本文深入解析ClassPathResource的构造器用法和类加载器选择,通过实例演示如何正确读取资源,并帮你避开找不到文件的常见陷阱,让你的资源加载更稳健

前言

ClassPathResource读取文件

ClassPathResource 表示从类路径获取资源,它使用线程上下文类加载器、给定的类加载器来加载资源。classpath 资源存在于类路径中的文件系统中或 jar 包里。

ClassPathResource 常用构造器

public ClassPathResource(String path);
public ClassPathResource(String path, @Nullable ClassLoader classLoader);
public ClassPathResource(String path, @Nullable Class<?> clazz);

示例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

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文