Spring Read Classpath Resource using ResourceLoader

In this Java Spring Framework tutorial, we learn how to use the ResourceLoader class from Spring Core module to read Resource files from classpath and convert the file to Java String object.

For example, we have a text file located at /src/main/resources/data.json in the Spring application project.

Next step, we implement a new class named ResourceService and implement two methods to read the data.json file as a Resource object and as a String object.

ResourceService.java

import java.io.IOException;
import java.io.InputStream;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;

@Service
public class ResourceService {
	
	@Autowired
	private ResourceLoader resourceLoader;
	
	public Resource readDataResource() {
		Resource resource = resourceLoader.getResource("classpath:data.json");
		return resource;
	}
	
	public String readDataResourceAsString() throws IOException {
		Resource resource = resourceLoader.getResource("classpath:data.json");
		InputStream inputStream = resource.getInputStream();
		byte[] fileData = FileCopyUtils.copyToByteArray(inputStream);
		String outputString = new String(fileData);
		return outputString;
	}
}

How to use the ResourceService class.

Firstly, declare the resourceService object.

@Autowired
private ResourceService resourceService;

How to read file in classpath and return Resource object.

Resource resource = resourceService.readDataResource();

How to read the text file in classpath and return as a String object.

String data = resourceService.readDataResourceAsString();

Happy Coding 😊