Get the App
SLTechnology News&Howtos  ›  Development  › 

How to read files under resources when SpringBoot is deployed to Linux

Shulou Source: shulou.com Published: 2022-06-01 01:10:40 10月04日 Update

This article focuses on "how to read files under resources when SpringBoot is deployed to Linux". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to read files under resources when SpringBoot is deployed to Linux.

Background

In normal business development, we usually put some fixed resource files under the resources folder, and get the files through the relative path when using them, which is a very simple function.

It seems that there are some small holes, such as the contents of the obtained files are garbled or the files cannot be read.

Read garbled code

This is very simple, ha. Specify in the maven plug-in that the files to be obtained later will not be compiled and will be typed into the package as is.

Org.apache.maven.plugins maven-resources-plugin sql xlsx xls reads files

This is a small pit, and it took an hour or two to find the problem. Despair

First list two absolutely not feasible, the main reason is that the re-development environment is no problem, running production can not pass

Method 1: File currentFolder = ResourceUtils.getFile ("classpath:excelTemplate/model.xls"); method 2: this.class.getResourceAsStream ("excelTemplate/model.xls")

Here are some possible ways to do it, but there are also some pitfalls. The pit was caused by an accident.

Method 1: Resource resource = new ClassPathResource ("excelTemplate/model.xls"); InputStream resourceAsStream = resource.getInputStream (); method 2: InputStream resourceAsStream = Thread.currentThread (). GetContextClassLoader (). GetResourceAsStream ("excelTemplate/model.xls")

These two methods are absolutely easy to use. Some friends may have reported an error when getting the file. If there is also an error, you can open it locally and try it now to see if the file is damaged.

With a picture and a truth, it definitely works.

Do not misunderstand that the program does run on Linux. In order to verify it, use the development tool Remote to debug remotely to facilitate screenshots.

At this point, I believe you have a deeper understanding of "how SpringBoot is deployed to Linux to read files under resources". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Tags: File method content development two garbled easy to use pit problem learning practical deeper accident despair business middle finger interest function reason as is Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft MariaDB Shulou Technology NVidia Docker