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 us
Here is one way of loading classpath resources.
Resource resource = applicationContext.getResource("classpath:xyz.xml");
InputStream is = 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")
You can add a field with annotation @Value
to your bean:
@Value("classpath:xyz.xml")
private Resource resource;
And then simply:
resource.getInputStream();
Best working code in Dec 14, 2019 (Spring version 5.1.0.RELEASE)
import org.springframework.core.io.Resource;
import org.springframework.core.io.ClassPathResource;
import java.io.File;
import java.io.InputStream;
Resource resource = new ClassPathResource("xyz.xml");
InputStream input = resource.getInputStream();
File file = resource.getFile();
See this for more details