Read a File from Resources in Spring Boot

Learn to read a file from the ‘/resources’ folder in a Spring boot application using ClassPathResource class, ResourceLoader interface or @Value annotation.

@Autowired
private ResourceLoader resourceLoader;

public void method(){

	Resource resource = resourceLoader.getResource("classpath:filename.txt");
	File file = resource.getFile());
	//...
}

//OR

Resource resource = new ClassPathResource("classpath:filename.txt");

//OR

@Value("classpath:filename.txt")
Resource resource;

To learn more about resource resolution in Spring, continue reading this tutorial.

1. Every File is a Resource in Spring

Spring’s Resource interface is used for abstracting access to low-level resources. After getting access to the Resource, we can use all its methods to get the file details and file content.

For quick reference, some of the important methods from the Resource interface are:

public interface Resource extends InputStreamSource {

    boolean exists();
    boolean isOpen();
    URL getURL() throws IOException;
    File getFile() throws IOException;
    Resource createRelative(String relativePath) throws IOException;
    String getFilename();
    String getDescription();
}

2. Resource Types in Spring

There are a number of Resource implementations inbuilt in Spring such as

  • ClassPathResource: loads a resource from the classpath. We can specify the path to the resource relative to the root of the classpath. It supports resolution as java.io.File if the class path resource resides in the filesystem but not for resources in a JAR. It recognizes the special prefix 'classpath:'on the string path.
  • UrlResource: Loads a resource from a URL. We can specify the URL of the resource with prefix 'http:' or ‘file:‘ if it is a file protocol.
  • FileSystemResource: Loads a resource from the file system. We can specify the absolute path to the resource on the file system with prefix 'file:'.
  • ServletContextResource: Loads a resource from the ServletContext. We can specify the path to the resource relative to the ServletContext. It does not use any prefixes.
@Autowired
ResourceLoader resourceLoader;

//Read resource

Resource classPathResource = resourceLoader.getResource("classpath:file.txt");
Resource urlResource = resourceLoader.getResource("http://example.com/file.txt");
Resource fileSystemResource = resourceLoader.getResource("file:/path/to/file.txt");
Resource servletContextResource = resourceLoader.getResource("/WEB-INF/file.txt");

//Get file content

File file = resource.getFile());

3. Use ClassPathResource to Read from ‘/resources’ Directory

All files placed in the /resources directory are placed in the application root ‘/’ at the build time. We can access them using the ClassPathResource class using the following approaches.

3.1. Using ResourceLoader or ApplicationContext

Instead of using the constructor, we can also use ResourceLoader for loading resources. File paths can be fully qualified URLs, e.g. "file:C:/test.dat" or "classpath:test.dat". It also supports relative file paths, e.g. "WEB-INF/test.dat".

Note that ResourceLoader is automatically autowired using Spring’s dependency injection.

All application contexts implement the ResourceLoader interface, and therefore all application contexts may be used to obtain Resource instances.

@Autowired
private ApplicationContext ctx;

Resource resource = ctx.getResource("classpath:data.txt");
File file = resource.getFile());

3.2. Using Constructor

We can pass the file path along with the prefix to the constructor of a resource class, and Spring will automatically load it for us.

Resource resource = new ClassPathResource("classpath:data.txt");

File file = resource.getFile();
String content = new String(Files.readAllBytes(file.toPath()));

To read a file from inside a jar or war file (that has not been extracted by the application server), please use resource.getInputStream().

Resource resource = new ClassPathResource("classpath:data.txt");

InputStream inputStream = resource.getInputStream();

try {
    byte[] bdata = FileCopyUtils.copyToByteArray(inputStream);
    String content = new String(bdata, StandardCharsets.UTF_8);
    LOGGER.info(data);
} catch (IOException e) {
    LOGGER.error("IOException", e);
}

3.3. Using @Value Annotation

We can also directly inject a file path into a Spring bean using the @Value annotation. Note that it eagerly loads the file.

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

//Inside some method
File file = resource.getFile();

4. Conclusion

Spring offers different implementations of the Resource interface to serve the resources from various sources, such as:

  • ClassPathResource: Loads a resource from the classpath using the ‘classpath:’ prefix.
  • UrlResource: Loads a resource from a URL with prefixes like ‘http:’ or ‘file:’.
  • FileSystemResource: Loads a resource from the file system using the ‘file:’ prefix.
  • ServletContextResource: Loads a resource from the ServletContext without any prefixes.

This tutorial discussed the ClassPathResource to read the files (JSON, XML files etc.) from the ‘/src/main/resources‘ directory.

Drop me your questions related to the read file from the resources folder in Spring.

Happy Learning !!

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode