Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC : read file from src/main/resources

Tags:

spring-mvc

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.

like image 701
Manish Kumar Avatar asked Feb 28 '14 13:02

Manish Kumar


People also ask

How do I read a file from src main resources?

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.

How do you get the src main resources path in Spring MVC?

Resource resource = new ClassPathResource(fileLocationInClasspath); InputStream resourceInputStream = resource. getInputStream();


4 Answers

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.

like image 119
NimChimpsky Avatar answered Oct 20 '22 03:10

NimChimpsky


For spring based application you can take advantage of ResourceUtils class.

File file = ResourceUtils.getFile("classpath:xyz.xml")
like image 37
Usman Avatar answered Oct 20 '22 02:10

Usman


Here is one way of loading classpath resources.

Resource resource = applicationContext.getResource("classpath:xyz.xml");
InputStream is = resource.getInputStream();
like image 14
Robby Pond Avatar answered Oct 20 '22 03:10

Robby Pond


You can add a field with annotation @Value to your bean:

@Value("classpath:xyz.xml")
private Resource resource;

And then simply:

resource.getInputStream();
like image 12
k13i Avatar answered Oct 20 '22 02:10

k13i