Java && File

本文详细介绍了在SpringBoot项目中如何使用ClassPathResource获取类路径下的文件绝对路径,以及通过各种方式获取InputStream,包括使用@Value注解、ResourceLoader、默认ClassLoader等。
摘要由CSDN通过智能技术生成

SpringBoot get file path

通過ClassLoader獲得class path,Debug 或者 Release 不同。

加載Bean file

@ImportResource(locations = {“classpath:bean-spring.xml”})

get file

@Value(“classpath:data/input.txt”)
private Resource inputResource;

ClassPathResource resource = new ClassPathResource(“data/input.txt”, this.getClass().getClassLoader());

ResourceLoader resourceLoader = new DefaultResourceLoader();
Resource inputFile = resourceLoader.getResource(“data/input.txt”);

ClassPathResource獲得文件絕對路徑

import org.springframework.core.io.ClassPathResource;

application-dev.yml
upload:
file-path: public\avatar
@ConfigurationProperties(prefix = "upload")
public class UploadContext {
private String filePath;
ClassPathResource resource = new ClassPathResource(filePath);
absoluteFileRootPath = resource.getFile().toString();
return absoluteFileRootPath;

在Class中get file path

/**
Debug模式下
D:/abc/target/test-classes/
**/
String path1 = ClassUtils.getDefaultClassLoader().getResource("").getPath();
String path2 = ResourceUtils.getURL("classpath:").getPath();


/**
D:/abc/target/classes/
**/
String path3 = 當前類.class.getProtectionDomain().getCodeSource().getLocation().getFile();

/**
D:/abc/target/classes/com/book/abc/service/report/
**/
String path4 = this.getClass().getResource("").getPath();


/**
Debug
D:/abc/target/test-classes/
**/
String path5 = this.getClass().getResource("/").getPath();
String path6 = JasperReportService.class.getClassLoader().getResource("").getPath();
String path7 = Thread.currentThread().getContextClassLoader().getResource("").getPath();

Object 的getClass 獲得 input Stream

InputStream inputStream = getClass().getResourceAsStream("/co/te/jasperreport/test.jrxml");
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值