SoFunction
Updated on 2025-04-22

How to read files under Resource

SpringBoot project is built into a jar to run, how to correctly read the file in resource

After the SpringBoot project is packaged into a jar file, it cannot read the contents in the jar file.

It is summarized that there are generally four ways to read files:

The first type

ClassPathResource classPathResource = new ClassPathResource("excleTemplate/");
InputStream inputStream = ();

The second type

InputStream inputStream = ().getContextClassLoader().getResourceAsStream("excleTemplate/");

The third type

InputStream inputStream  = ().getResourceAsStream("/excleTemplate/");

The fourth type

File file = ("classpath:excleTemplate/");
InputStream inputStream = new FileInputStream(file);

The first three methods can be read in the development environment (IDE) and the production environment (linux is deployed into jar packages). The fourth method can be read only in the development environment, but the production environment fails to read.

The main reason is that springboot has built-in tomcat, which is a jar package after packaging, and cannot directly read files in the jar package, and can only be read through the class loader.

The first three types can be read to the same extent. The underlying code can be viewed directly through the class loader to read the file stream. The class loader can read the compiled class files in the jar package, and of course, it can also read the excle templates in the jar package.

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.