Spring Read Classpath Resource using ClassPathResource

Tags: Spring Framework Resource ClassPathResource Classpath

In this Java Spring Framework tutorial, we learn how to use the ClassPathResource class of Spring Core module to read files located in the resources directory of the Spring application project.

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 and return it as a Resource object or String object.

ResourceService.java

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

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;

public class ResourceService {
	
	public Resource readDataResource() {
		Resource resource = new ClassPathResource("data.json");
		return resource;
	}
	
	public String readDataResourceAsString() throws IOException {
		Resource resource = new ClassPathResource("data.json");
		InputStream inputStream = resource.getInputStream();
		byte[] fileData = FileCopyUtils.copyToByteArray(inputStream);
		String outputString = new String(fileData);
		return outputString;
	}

}

How to use ResourceService class

How to read Classpath file and return Resource object

ResourceService resourceService = new ResourceService();		
Resource resource = resourceService.readDataResource();

How to read Classpath file and return String value

ResourceService resourceService = new ResourceService();
String data = resourceService.readDataResourceAsString();

Happy Coding 😊