49

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.

1

5 Answers 5

85
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.

Sign up to request clarification or add additional context in comments.

2 Comments

In this case, fileLocationInClasspath should not start with "classpath:".
does this work if I need to read a folder from src/main/resources
28

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

File file = ResourceUtils.getFile("classpath:xyz.xml") 

3 Comments

Read file from resources folder – Spring Example howtodoinjava.com/java/io/read-file-from-resources-folder
The documentation states that it's "Mainly for internal use within the framework."
14

Here is one way of loading classpath resources.

Resource resource = applicationContext.getResource("classpath:xyz.xml"); InputStream is = resource.getInputStream(); 

1 Comment

Hey Robby, this is super helpful but Kenji and I are wondering how you would then parse a file line by line from the input stream.
12

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

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

And then simply:

resource.getInputStream(); 

Comments

1

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

1 Comment

Using ClassPathResource is exactly what I was looking for since it eliminates the need to write classpath: in the file path. Thanks for sharing this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.