The road so far….

April 21, 2010

Spring: Load resources from any location(Classpath Jar, FilePath etc)

Filed under: java — Tags: , — Rahul Sharma @ 11:47 pm

Loading proper resources esp configuration files, properties files etc is an important aspect of any application. In one of my projects I was supposed to load a resource(configuration file) from a dependency jar but the same resource was also required to be loaded from a specified path location in another part of the same application .  We can do this using the ClassLoader‘s and URL for loading the Classpath resource and using File for the file system resource. OR, we can use spring Resource api to get the difference sort out for us.

After Loading the resource we were supposed to get the InputStream from it pass it to the configuration loader API.

The Spring Resource interface is a useful interface and has quite a few implementations that can suit all kinds of different purposes. It provides  Resource.getInputStream API to get an InputStream from the underlying Resource. The ClassPathResource can be used to load resources from the class path while FileSystemResource can be used to load from file location and so on.

Using  java Api we can do it in the following manner:

  1. For ClassPath Resource:
      URL loadedResource = this.getClass().getClassLoader().getResource(“Resourcename.xml”);
      InputStream inputStream = loadedResource.openStream();
  2. For File Resource:

InputStream stream= new FileInputStream(new File(“Filename”));

Using Spring it became quite simple:

Resource resource=new CLassPathResource(“resourcename”);//FileSystemResource(“MyResource”)




Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: