【SpringBoot】三种方式,教你读取 jar 包中的 resources 目录下的文件 您所在的位置:网站首页 如何查看jar包里的类别 【SpringBoot】三种方式,教你读取 jar 包中的 resources 目录下的文件

【SpringBoot】三种方式,教你读取 jar 包中的 resources 目录下的文件

2024-07-02 19:06| 来源: 网络整理| 查看: 265

读取 resources 目录下的文件路径时,需要注意一点:在本地开发时,我们是能够通过代码获取到这个文件的绝对路径的(如:在 c 盘下或者 d 盘下的);但部署后,项目是通过打成 jar 包运行的,里面的文件是没有实际路径的(只有相对于项目名的相对路径)。

因为最后肯定是打包部署的,所以掌握针对后者的这种方式来读取文件是很有必要的。

代码图如下: 在这里插入图片描述

方式一:(重要)

通过 T.class.getClassLoader().getResourceAsStream() 方法。如:我要读取 config 文件夹下的 test.properties 文件:

这是一个公共方法,用来读取文件中的内容的方法,下面就不再重复了:

public static void printFileContent(Object obj) throws IOException { if (null == obj) { throw new RuntimeException("参数为空"); } BufferedReader reader = null; // 如果是文件路径 if (obj instanceof String) { reader = new BufferedReader(new FileReader(new File((String) obj))); // 如果是文件输入流 } else if (obj instanceof InputStream) { reader = new BufferedReader(new InputStreamReader((InputStream) obj)); } String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); }

读取方法:

public class ResourceUtil { public void getResource(String fileName) throws IOException{ InputStream in = this.getClass().getClassLoader().getResourceAsStream(fileName); printFileContent(in); } public static void main(String[] args) throws IOException { new ResourceUtil().getResource("config/test.properties"); } }

即使是一个 jar 包,也依旧能读取到。

此方法默认是从 classpath 路径(即:src 或 resources 路径下)下查找文件的,所以,路径前不需要加 “/”。

方式二:(重要)

通过 T.class..getResourceAsStream() 方法。

public void getResource2(String fileName) throws IOException{ InputStream in = this.getClass().getResourceAsStream("/" + fileName); printFileContent(in); } public static void main(String[] args) throws IOException { new ResourceUtil().getResource2("config/test.properties"); }

此方法默认也是从 classpath 路径(即:src 或 resources 路径下)下查找文件的,但它的路径前为什么需要加 “/” 呢?

这个是跟要读取的文件与当前.class 文件的位置有关。

看看编译后的文件路径:

在这里插入图片描述 当前文件 ResourceUtil.class 与要加载的文件 test.properties 的位置如上: 很显然 test.properties 和 ResourceUtil.class 不在同一个文件夹下。

那读取的时候是要带上相对路径的,那么,这会有两种情况:

相对于当前类 ResourceUtil,路径前是不需要加 “/”相对于项目名(即:编译后的 classes 文件夹),路径前是需要加 “/”

举例:

如果 test.properties 和 ResourceUtil 在同一个文件夹下,那么:this.getClass().getResourceAsStream(“test.properties”)如果 test.properties 和 ResourceUtil 不在同一个文件夹下,那么:this.getClass().getResourceAsStream(“/config/test.properties”)

如果测试,不要在源文件下添加配置文件,因为编译后,在相应的路径下看不见此配置文件。可以使用 Test.java 代替。

即使是一个 jar 包,也依旧能读取到。

方式三:(重要)

通过 ClassPathResource 方法:

public void getResource3(String fileName) throws IOException{ ClassPathResource classPathResource = new ClassPathResource(fileName); printFileContent(classPathResource.getInputStream()); } public static void main(String[] args) throws IOException { new ResourceUtil().getResource3("config/test.properties"); }

path 前加不加 “/” 无所谓。

即使是一个 jar 包,也依旧能读取到。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有