Spring – Read file from resources folder

In Spring, we can use ClassPathResource or ResourceLoader to get files from classpath easily.

P.S Tested with Spring 5.1.4.RELEASE

1. src/main/resources/

For example, an image file in the src/main/resources/ folder

resources

2. ClassPathResource


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

import java.io.File;
import java.io.InputStream;

	Resource resource = new ClassPathResource("android.png");

	InputStream input = resource.getInputStream();

	File file = resource.getFile();

3. ResourceLoader


import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.File;
import java.io.InputStream;


	@Autowired
    ResourceLoader resourceLoader;
	
	Resource resource = resourceLoader.getResource("classpath:android.png");

	InputStream input = resource.getInputStream();

	File file = resource.getFile();

4. ResourceUtils

Please DO NOT use this ResourceUtils even it works, this class is mainly for internal use within the framework. Read the ResourceUtils JavaDocs


import org.springframework.util.ResourceUtils;

	File file = ResourceUtils.getFile("classpath:android.png");

References

7 comments on “Spring – Read file from resources folder

  1. Trying to access my resource file in jar. Its working if i’m running from IDE but if i’m running the jar then giving an issue. java.io.FileNotFoundException: class path resource [iam-jks-1.4.5.jks] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/test/Documents/event-ingestion-service/target/event-ingestion-microservice-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/iam-jks-1.4.5.jks

    Reply
    1. I am aslo facing same isssue any solution please

      Reply
  2. Hi mkyoung!

    Is there a way to read from a classpath of an external library (included in my classpath obiously)

    Reply
  3. Hi, I’m using ClassPathResource and ResourceLoader but I am get error : class path resource [image.png] cannot be opened because it does not exist

    Reply

Leave a Comment

Your email address will not be published. Required fields are marked *