码迷,mamicode.com
首页 > 编程语言 > 详细

Read file in Spring

时间:2020-01-13 23:40:06      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:Servle   cat   src   creat   under   span   tab   ecif   inter   

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

标签:Servle   cat   src   creat   under   span   tab   ecif   inter   

原文地址:https://www.cnblogs.com/stupid-pig/p/12189791.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!