Learn to read a file from resources folder in spring boot application using ClassPathResource and ResourceLoader classes.
For demo purpose, I have added data.txt
file in resources folder with below text content.
HowToDoInJava.com Java Tutorials Blog |
1. ClassPathResource
ClassPathResource is a Resource
implementation for class path resources.
It supports resolution as java.io.File
if the class path resource resides in the file system, but not for resources in a JAR. To read a file inside a jar or war file, please use resource.getInputStream()
method.
import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.core.io.ClassPathResource; import org.springframework.core.io.Resource; import org.springframework.util.FileCopyUtils; @SpringBootApplication public class Application implements CommandLineRunner { final Logger LOGGER = LoggerFactory.getLogger(getClass()); public static void main(String[] args) { SpringApplication app = new SpringApplication(Application. class ); app.run(args); } @Override public void run(String... args) throws Exception { Resource resource = new ClassPathResource( "classpath:data.txt" ); InputStream inputStream = resource.getInputStream(); try { byte [] bdata = FileCopyUtils.copyToByteArray(inputStream); String data = new String(bdata, StandardCharsets.UTF_8); LOGGER.info(data); } catch (IOException e) { LOGGER.error( "IOException" , e); } } } |
$ java -jar target\springbootdemo- 0.0 . 1 -SNAPSHOT.jar HowToDoInJava.com Java Tutorials Blog |
2. Read file from resources using ResourceLoader
Instead of using ClassPathResource
, we can also use ResourceLoader for loading resources (e.. class path or file system resources).
An ApplicationContext
is required to provide this functionality, plus extended ResourcePatternResolver
support.
File paths can be fully qualified URLs, e.g. "file:C:/test.dat"
or "classpath:test.dat"
. It support relative file paths, e.g. "WEB-INF/test.dat"
.
final Logger LOGGER = LoggerFactory.getLogger(getClass()); @Autowired ResourceLoader resourceLoader; @Override public void run(String... args) throws Exception { Resource resource = resourceLoader.getResource( "classpath:data.txt" ); InputStream inputStream = resource.getInputStream(); try { byte [] bdata = FileCopyUtils.copyToByteArray(inputStream); String data = new String(bdata, StandardCharsets.UTF_8); LOGGER.info(data); } catch (IOException e) { LOGGER.error( "IOException" , e); } } |
$ java -jar target\springbootdemo- 0.0 . 1 -SNAPSHOT.jar HowToDoInJava.com Java Tutorials Blog |
Drop me your questions related to spring read file from resources folder.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.