I have a maven Spring project, there is xml
file inside src/main/resources/xyz.xml
. How can I read it inside spring MVC controller.
I am using
InputStream is = getClass().getResourceAsStream("classpath:xyz.xml");
but is
is null
.
Using Java getResourceAsStream() This is an example of using getResourceAsStream method to read a file from src/main/resources directory. First, we are using the getResourceAsStream method to create an instance of InputStream. Next, we create an instance of InputStreamReader for the input stream.
Resource resource = new ClassPathResource(fileLocationInClasspath); InputStream resourceInputStream = resource. getInputStream();
Resource resource = new ClassPathResource(fileLocationInClasspath);
InputStream resourceInputStream = resource.getInputStream();
using ClassPathResource and interface resource. But make sure you are copying the resources directory correctly (using maven), and its not missing, for example if running tests as part of test context.
For spring based application you can take advantage of ResourceUtils class.
File file = ResourceUtils.getFile("classpath:xyz.xml")
Here is one way of loading classpath resources.
Resource resource = applicationContext.getResource("classpath:xyz.xml");
InputStream is = resource.getInputStream();
You can add a field with annotation @Value
to your bean:
@Value("classpath:xyz.xml")
private Resource resource;
And then simply:
resource.getInputStream();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With