I am working on a Spring Boot application. I need to parse an XML file (countries.xml) on start. The problem is that I do not understand where to put it so that I could acce
I use Spring Boot, my solution to the problem was
"src/main/resources/myfile.extension"
Hope it helps someone.
You need to use following construction
InputStream in = getClass().getResourceAsStream("/yourFile");
Please note that you have to add this slash before your file name.
Because java.net.URL is not adequate for handling all kinds of low level resources, Spring introduced org.springframework.core.io.Resource. To access resources, we can use @Value annotation or ResourceLoader class. @Autowired private ResourceLoader resourceLoader;
@Override public void run(String... args) throws Exception {
Resource res = resourceLoader.getResource("classpath:thermopylae.txt");
Map<String, Integer> words = countWords.getWordsCount(res);
for (String key : words.keySet()) {
System.out.println(key + ": " + words.get(key));
}
}
While working with Spring Boot application, it is difficult to get the classpath resources using resource.getFile()
when it is deployed as JAR as I faced the same issue.
This scan be resolved using Stream which will find out all the resources which are placed anywhere in classpath.
Below is the code snippet for the same -
ClassPathResource classPathResource = new ClassPathResource("fileName");
InputStream inputStream = classPathResource.getInputStream();
content = IOUtils.toString(inputStream);
You can use following code to read file in String from resource folder.
final Resource resource = new ClassPathResource("public.key");
String publicKey = null;
try {
publicKey = new String(Files.readAllBytes(resource.getFile().toPath()), StandardCharsets.UTF_8);
} catch (IOException e) {
e.printStackTrace();
}
Just use Spring type ClassPathResource.
File file = new ClassPathResource("countries.xml").getFile();
As long as this file is somewhere on classpath Spring will find it. This can be src/main/resources
during development and testing. In production, it can be current running directory.
EDIT: This approach doesn't work if file is in fat JAR. In such case you need to use:
InputStream is = new ClassPathResource("countries.xml").getInputStream();