SoFunction
Updated on 2025-03-08

How to get files under src/main/resource path

SpringBoot gets the file under src/main/resource path

The following ResourceUtils uses the spring-core toolkit, under the package

File file = (ResourceUtils.CLASSPATH_URL_PREFIX+"static/imgs/");

However, if the Boot project is turned into a jar package, the file will not be retrieved and the following error will not be found:

/E:/test/demo-1.1.!/BOOT-INF/classes!/static/imgs/

Because after being typed into a jar package, it is no longer like the disk folder storage, so if you want to type into a jar package, you can first read the stream of the file in the jar as follows, and then transfer the stream to your own needs (this method can also be used to type into war)

InputStream  inputStream = ().getResourceAsStream("/static/imgs/");

After SpringBoot is made into a jar package, read the files in the resources directory

General Methods

Properties pps = new Properties();
File file = ("classpath:");
(new FileReader(file));

At this time, an error will be reported when packaged as a jar:

During debugging, the file is a directory that actually exists on the disk. At this time, by obtaining the file path, it can be read normally because the file does exist.

After packaging it into a jar, the file actually exists in the resource file in the jar file, and there is no real path on the disk. Therefore, the file cannot be obtained correctly through the ().getResource("") method.

The correct way

Use stream to process, and set the encoding utf-8 when reading streams at the same time

Using InputStream inputStream=().getResourceAsStream("") specifies that the resource path to be loaded is consistent with the path of the package in which the current class is located. Therefore, the file can be read normally.

Properties pps = new Properties();
InputStream stream = getClass()
                    .getClassLoader()
                    .getResourceAsStream(""); 
BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
(br);

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