Loading and Reading Resource Files for SpringBoot Project

  • 2021-12-04 10:09:29
  • OfStack

Directory through Resource interface Manual loading
Automatic conversion via @ Value
Load via ResourceLoader
Loading resources using ResourceUtils Read the contents of the resource Read through an File object
Read through InputStream object
Summary at the end of the article

This article chats 1 in the SpringBoot application, accesses the loading class path (classpath) in the file content many methods.

Through the Resource interface

Resource interface abstracts a lower-level way to manage resources, which can process all kinds of file resources in a unified way. Here are several ways to get resource instances.

Manual loading

To access the files in the classpath, we can directly use ClassPathResource to load the content, such as:


new ClassPathResource("data/resource-data.txt");

By default, ClassPathResource chooses between the context class loader of the thread and the default system class loader to delete the boilerplate file. We can also specify the class loader directly, such as:


new ClassPathResource("data/resource-data.txt", this.getClass().getClassLoader());

Or by specifying the class loader of the class:


new ClassPathResource("data/resource-data.txt", Employee.class.getClassLoader());

From an Resource object, we can easily convert it to an InputStream or an File object.

The above-mentioned methods are all relative to the address of the classpath. If you want to specify the relative path of a class, we can define it by specifying a specific class, such as:


new ClassPathResource("../../../data/resource-data.txt", Example.class).getFile();

This is the relative path relative to Example. In practical use, it is not recommended to get files whose relative paths through classes. This binds the class to the relative coordinates of the file. If you modify the package path of the class but forget to modify the file location, an error will occur. Moreover, everyone now uses package manager management such as Maven. You can directly define configuration files in resources directory and load files with the relative address of ClassPath.

Automatic conversion via @ Value

We can also use @ Value to directly inject Resource objects, such as:


@Value("classpath:data/resource-data.txt")
Resource resourceFile;

@ Value also supports other loading protocols, such as file: or url:.

Load via ResourceLoader

We can also use injecting ResourceLoader to implement lazy loading of resources, for example, injecting ResourceLoader instances first:


@Autowired
ResourceLoader resourceLoader;

Then, where we need it, load the resources through the ResourceLoader instance:


resourceLoader.getResource("classpath:data/resource-data.txt");

In Spring, ApplicationContext implements ResourceLoader, so we can also load resources directly through ApplicationContext instances, such as:


ApplicationContext context;

public Resource loadEmployeesWithApplicationContext() {
    return context.getResource("classpath:data/resource-data.txt");
}

Loading resources using ResourceUtils

In Spring, there is also a tool class ResourceUtils, which can easily obtain the resources in the classpath. But as you can see from Javadoc of this class, this class is mainly used inside Spring, which means that this usage is not recommended. But we can know one thing:


public File loadEmployeesWithSpringInternalClass() 
  throws FileNotFoundException {
    return ResourceUtils.getFile(
      "classpath:data/resource-data.txt");
}

We can understand its internal implementation, but we still suggest using other more standard practices.

Read the contents of the resource

All of the above have obtained Resource resources in various ways. Next, let's talk about how to obtain the data of resource objects.

For example, our resource file reads as follows:

Site: https://www.howardliu.cn
Author: Looking at the mountains
Official number: Look at the cabin in the mountain

Pay attention to the welfare of the public number

Read through File object

We can use the getFile method to get the File instance, and we can read the file in the way of reading the File object, such as:


@Test
File resource = new ClassPathResource("data/resource-data.txt").getFile();
String content = new String(Files.readAllBytes(resource.toPath()));

However, this method is not suitable for reading files in jar packages. Since many applications are deployed through FatJar, we need to find other methods.

Read through an InputStream object

The reason why File object is not suitable for reading resources in jar package is that the file path format is different, so we can directly read the resource content in the form of stream, so there is no problem of file path. For example:


new ClassPathResource("data/resource-data.txt", this.getClass().getClassLoader());
0

Read complete.

Summary at the end of the article

This paper explains from two methods: loading resources and reading contents, and gives a variety of reading methods.


Related articles: