Resource loader : Spring ResourceLoader interface is used to load external data(i.e text file, media file, image file) in Spring application using the method getResource(). We can use three ways for loading resources :
URL Path :
Resource resource = appContext.getResource("file:c:\\testing.txt");
File System :
Resource resource = appContext.getResource("url:http://www.yourdomain.com/testing.txt");
Class Path :
Resource resource = appContext.getResource("classpath:com/bhagwan/common/testing.txt");
Here, I explain example with getResource() method :
package com.bhagwan.common;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.io.Resource;
public class ResourceApplication
{
public static void main( String[] args )
{
ApplicationContext appContext =
new ClassPathXmlApplicationContext(new String[] {"If-you-have-any.xml"});
Resource resource =
appContext.getResource("classpath:com/bhagwan/common/testing.txt");
try{
InputStream is = resource.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
0 Comment(s)