Read file in Spring

Posted stupid-pig

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Read file in Spring相关的知识,希望对你有一定的参考价值。

Spring ResourceLoader provides a unified getResource() method for us to retrieve an external resource by a resource path.

1. Resource interface represents a resource

Resource is a general interface in Spring for representing an external resource.

 

Spring provides following 6 implementations for the Resource interface.

  1. UrlResource
  2. ClassPathResource
  3. FileSystemResource
  4. ServletContextResource
  5. InputStreamResource
  6. ByteArrayResource

We can specify different prefixes for creating path to load resources from different locations.

PrefixExampleExplanation
classpath: classpath:com/myapp/config.xml Loaded from the classpath.
file: file:///data/config.xml Loaded as a URL from the filesystem.
http: https://myserver/logo.png Loaded as a URL.
(none) /data/config.xml Depends on the underlying ApplicationContext.

 

2. ResourceLoader

It is used for loading resources. It has two methods:

//Expose the ClassLoader used by this ResourceLoader.
ClassLoader getClassLoader()
 
//Return a Resource handle for the specified resource location.
Resource getResource(String location)

The getResource() method will decide which Resource implementation to instantiate according to the resource path.

Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");

 

3. Loading resource with ApplicationContext

In Spring, all application contexts implement the ResourceLoader interface. Therefore, all application contexts may be used to obtain Resource instances.

 

To get the reference of ApplicationContext, implement the ApplicationContextAware interface.

Resource banner = ctx.getResource("file:c:/temp/filesystemdata.txt");

 

4. Loading resource with ResourceLoaderAware

To demonstrate the various examples below, I have placed a file with matching name in different locations and I will show to load each one of them.

CustomResourceLoader.java is written as below which print the content of loaded resource file into console.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
 
public class CustomResourceLoader implements ResourceLoaderAware 
{
    private ResourceLoader resourceLoader;
 
    public void setResourceLoader(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }
 
    public void showResourceData() throws IOException 
    {
        //This line will be changed for all versions of other examples
        Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");
 
        InputStream in = banner.getInputStream();
 
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
 
        while (true) {
            String line = reader.readLine();
            if (line == null)
                break;
            System.out.println(line);
        }
        reader.close();
    }
}

And applicationContext.xml file entry for this file is as below:

<bean id="customResourceLoader" class="com.howtodoinjava.demo.CustomResourceLoader"></bean>

To test the CustomResourceLoader bean and call the showResourceData() method, below code has been used:

@SuppressWarnings("resource")
public static void main(String[] args) throws Exception 
{
    ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
 
    CustomResourceLoader customResourceLoader = (CustomResourceLoader) context.getBean("customResourceLoader");
 
    customResourceLoader.showResourceData();
}

技术图片 

5. Load external resources

5.1. Load resource from application root folder

Resource banner = resourceLoader.getResource("file:data.txt");

5.2. Load resource from class path

Resource banner = resourceLoader.getResource("classpath:classpathdata.txt");

5.3. Load resource from filesystem

Resource banner = resourceLoader.getResource("file:c:/temp/filesystemdata.txt");

5.4. Load resource from URL

Resource banner = resourceLoader.getResource("//howtodoinjava.com/readme.txt");

 

6. How to inject external files

In above example, we have hard coded the resource name in CustomResourceLoader which many of you may not like and want to make it configurable through context file. Use below code template to make external resource name configurable.

<bean id="customResourceLoader" class="com.howtodoinjava.demo.CustomResourceLoader">
 
    <property name="resource">
        <value>classpath:classpathdata.txt</value>
        <!-- or -->
        <value>file:data.txt</value> 
    </property>
 
</bean>

And CustomResourceLoader will be like below:

public class CustomResourceLoader {
 
    private Resource resource;
 
    public Resource getResource() {
        return resource;
    }
 
    public void setResource(Resource resource) {
        this.resource = resource;
    }
}

Upon context initialization, resource will be injected into ‘resource‘ property of CustomResourceLoader. The same code can be used in spring boot resourceloader example.

以上是关于Read file in Spring的主要内容,如果未能解决你的问题,请参考以下文章

Choose unique values for the 'webAppRootKey' context-param in your web.xml files! 错误的解决(代码片段

解决go: go.mod file not found in current directory or any parent directory; see ‘go help modules‘(代码片段

[Python] Read from a File in Python

[Python] Read from a File in Python

read obj in matlab

需要对特定 R 代码片段的解释