获取springboot打成jar后的classpath

在将子项目Utils打包为jar并部署到Linux平台后,遇到一个问题:工具类依赖的conf配置文件无法被正确读取。原本尝试通过文件系统路径访问,但在jar环境下失败。解决方案是通过`resource.getInputStream()`来访问jar内的classpath资源,从而解决了SpringBoot在jar环境下无法访问内部路径的问题。

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

项目需要另一个子项目Utils的一个util工具类,在A项目的maven中加入了该子项目

<dependency>
			<groupId>com.supconit.data.algorithm.platform</groupId>
			<artifactId>data_algorithm_util</artifactId>
			<version>1.1.00.190408-SNAPSHOT</version>
</dependency>

但是该工具类的执行依赖一个conf文件,把子项目Utils打成jar包后,发布到linux平台上,发现无法读取该配置文件,报错如下:

java.io.FileNotFoundException: class path resource [fdfs_client.conf] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/home/data_algorithm/data_algorithm_executor-1.1.00.190408-SNAPSHOT.jar!/BOOT-INF/lib/data_algorithm_util-1.1.00.190408-SNAPSHOT.jar!/fdfs_client.conf

修改之前的代码

 String path  = new ClassPathResource("fdfs_client.conf").getFile().getAbsolutePath();
 ClientGlobal.init(path);

修改之后的代码

 ClassPathResource classPathResource = new ClassPathResource("fdfs_client.conf");
            //创建临时文件,将fdfs_client.conf的值赋值到临时文件中,创建这个临时文件的原因是springboot打成jar后无法获取classpath下文件
            String tempPath =System.getProperty("java.io.tmpdir") + System.currentTimeMillis()+".conf";
            File f = new File(tempPath);
            IOUtils.copy(classPathResource.getInputStream(),new FileOutputStream(f));
            ClientGlobal.init(f.getAbsolutePath());

发布之后,问题解决,原因是因为打包后Spring试图访问文件系统路径,但无法访问JAR中的路径,因此必须使用resource.getInputStream()。

在使用Spring Boot时,可能会出现打成JAR运行后无法读取resources里的文件的问题。这是因为在JAR包中,资源文件会被打包到一个压缩文件中,而不是一个文件夹中。 解决这个问题有几种方法: 1. 使用Classloader获取资源 可以使用Java的Classloader获取JAR包中的资源。这种方法可行,但较繁琐。 举个例子: ```java ClassLoader classLoader = getClass().getClassLoader(); InputStream inputStream = classLoader.getResourceAsStream("file.txt"); ``` 这样做可以读取位于JAR包中的file.txt文件。 2. 使用Spring提供的ResourceLoader Spring提供了ResourceLoader来处理此问题。我们可以注入ResourceLoader并使用它读取资源。 举个例子: ```java @Autowired private ResourceLoader resourceLoader; public void readFile() throws IOException { Resource resource = resourceLoader.getResource("classpath:file.txt"); InputStream inputStream = resource.getInputStream(); } ``` 这个方法还可以处理其他类型的资源,例如网络资源等。 3. 使用FileSystemResource 我们可以使用FileSystemResource来读取文件。这种方法需要JAR包解压到文件夹中,然后使用FileSystemResource来读取文件。 ```java Resource resource = new FileSystemResource(file.txt); InputStream inputStream = resource.getInputStream(); ``` 但是这种方法会使JAR包无法单独使用。 总之,以上三种方法都可以解决打成JAR运行后无法读取resources里的文件的问题,我们可以根据实际情况选择其中一种方法。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值