其他分享
首页 > 其他分享> > Read file in Spring

Read file in Spring

作者:互联网

Learn different ways to load resources or files (e.g. text files, XML files, properties file, or image files) into the Spring application context. 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.

<style></style>  

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 (e.g. class path or file system resources). It has two methods:

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

To get the reference of ResourceLoader, implement the ResourceLoaderAware interface.

How to get resource
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.

How to get resource
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.

CustomResourceLoader.java
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:

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

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

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

spring-load-external-resource-example

5. Load external resources

5.1. Load resource from application root folder

To load file from application folder, use below template:

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

5.2. Load resource from class path

To load file from classpath, use below template:

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

5.3. Load resource from filesystem

To load file from filesystem outside the application folder, use below template:

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

5.4. Load resource from URL

To load file from any URL, use below template:

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

All above examples will load the resource file from their location and you can use them the way you want.

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.

beans.xml
<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:

CustomResourceLoader.java
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.

标签:resourceLoader,resource,Read,Spring,getResource,file,CustomResourceLoader,Resour
来源: https://www.cnblogs.com/stupid-pig/p/12189791.html