How do I load a resource and use its contents as a string in Spring

JavaSpring

Java Problem Overview


How can I load a Spring resource contents and use it to set a bean property or pass it as an argument constructor?

The resource contains free text.

Java Solutions


Solution 1 - Java

In one line try this to read test.xml:

String msg = StreamUtils.copyToString( new ClassPathResource("test.xml").getInputStream(), Charset.defaultCharset()  );

Solution 2 - Java

<bean id="contents" class="org.apache.commons.io.IOUtils" factory-method="toString">
    <constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
</bean>

This solution requires Apache Commons IO.

Another solution, suggested by @Parvez, without Apache Commons IO dependency is

<bean id="contents" class="java.lang.String">
    <constructor-arg>
        <bean class="org.springframework.util.FileCopyUtils" factory-method="copyToByteArray">
            <constructor-arg value="classpath:path/to/resource.txt" type="java.io.InputStream" />
        </bean>		
    </constructor-arg>
</bean>

Solution 3 - Java

Just read it :

    try {
        Resource resource = new ClassPathResource(fileLocationInClasspath);
        BufferedReader br = new BufferedReader(new InputStreamReader(resource.getInputStream()),1024);
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            stringBuilder.append(line).append('\n');
        }
        br.close();
        return stringBuilder.toString();
    } catch (Exception e) {
        LOGGER.error(e);
    }

Solution 4 - Java

This is one way of doing it without using any external library.. default provided by spring.. environment.properties file contains key value pairs...reference each value with ${key}

here in my example, I am keeping database props

<bean id="propertyConfigurer"
	class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="locations">
		<list value-type="org.springframework.core.io.Resource">
			<value>classpath:environment.properties</value>

		</list>
	</property>
</bean>
<bean id="mySQLdataSource"
	class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${JDBC.driver}" />
	<property name="url" value="${JDBC.URL}" />
	<property name="username" value="${JDBC.username}" />
	<property name="password" value="${JDBC.password}" />
</bean>

Solution 5 - Java

Update in 2021.

You can use Spring's Resource Interface to get the content of text file, and then use StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset()); to get the text.

An example as follow:

    @Value("classpath:appVersionFilePath")
    private Resource resource;

    @GetMapping(value = "/hello")
    public HttpResult<String> hello() throws IOException {
        String appVersion = StreamUtils.copyToString(resource.getInputStream(), Charset.defaultCharset());
        // ...
    }

Solution 6 - Java

daoway answer was very helpful, and following Adrian remark I am adding a configuration snippet similar to daoway's code

<bean id="contents" class="org.springframework.core.io.ClassPathResource">
	<constructor-arg value="path/to/resource.txt"/>
</bean>

From your component

	@Autowired
	private Resource contents;

    @PostConstruct
    public void load(){
    	try {
     		final InputStream inputStream = contents.getInputStream();
    			//use the stream 
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream ,1024);
            StringBuilder stringBuilder = new StringBuilder();
            String line;
            while ((line = br.readLine()) != null) {
                stringBuilder.append(line).append('\n');
            }
            br.close();
     }catch (IOException e) {
			LOGGER.error(message);
	 }
  }

Solution 7 - Java

Spring

    private String readResource(String fileName){
	ResourceLoader resourceLoader = new DefaultResourceLoader();
	Resource resource = resourceLoader.getResource("resourceSubfolder/"+fileName)
	try{
		 Reader reader = new InputStreamReader(resource.getInputStream());
		 return FileCopyUtils.copyToString(reader);
	} catch (IOException e){
		 e.printStackTrace();
	}
	return null;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAdrian BerView Question on Stackoverflow
Solution 1 - JavaN PiperView Answer on Stackoverflow
Solution 2 - JavaAdrian BerView Answer on Stackoverflow
Solution 3 - JavadaowayView Answer on Stackoverflow
Solution 4 - JavaChetanView Answer on Stackoverflow
Solution 5 - JavaQianyueView Answer on Stackoverflow
Solution 6 - JavaHaim RamanView Answer on Stackoverflow
Solution 7 - JavavitalinventView Answer on Stackoverflow