HOW TO: Read a file from jar and war files (java and webapp archive) ?

octobre 19, 2008

As many java programmers, i spent hours searching for the “good recipe” to read a txt file from my java archive to configure an application. The config file aren’t available to final users, so it should only help the programmer to configure his webapp, without having an external file / URL to check.

Reading a java archive would generally be done using the classloader of the JVM.

How to read from a jar file

The files you are looking to must be located in a directory named “classes” at the top of your src folder.
Unless your file exists, you will be able to open it as an URL or as a stream, using the application classloader.
To access to the class loader, just use your class, get the static ”class” instance pointer, and invoke getClassLoader method.
Then, use one of these two method:
getResourceAsStream() to have an input file
getResource() to have an URL object

If you try to open a file outside the classes folder, the classloader will throw a NullException.

InputStream in =
new InputStreamReader(FileLoader.class.getClassLoader().getResourceAsStream("file.txt") );

How to read from a war file

Here is what the tomcat documentation says about loading your own files shipped within your webapp archive:

WebappX – A class loader is created for each web application that is deployed in a single Tomcat 6 instance. All unpacked classes and resources in the /WEB-INF/classes directory of your web application archive, plus classes and resources in JAR files under the /WEB-INF/lib directory of your web application archive, are made visible to the containing web application, but to no others.

So it means you will use the /WEB-INF/classes directory. It means the code would be nearly the same as for a Desktop application jar file. Get a classloader from the classe you are coding (just change the name of it) and get your file.

The best way to look to a config file from a webapp is to implement the servlet method init().
Let’ try using the same code
InputStream in =
new InputStreamReader(FileLoaderServlet.class.getClassLoader().getResourceAsStream("file.txt") );

It works fine !

So just remember to put your into the right folder if you are getting an exception.

Reading files outside the classes folder ?

Theses articles will show you a simple way to achieve it for jar files:

http://java.sun.com/developer/JDCTechTips/2003/tt0122.html

For war files, don’t use the servlet container’s classloader, but use the ServletContext instead.

This method allows servlet containers to make a resource available to a servlet from any location, without using a class loader.

ServletContext context = getServletContext();
InputStream is = context.getResourceAsStream("/yourfilename.txt");

It is recommended to keep it under the /WEB-INF directory if you don’t want browers being able to access it.

The path must begin with a “/” and is interpreted as relative to the current context root. This method returns null if no resource exists at the specified path. For example ServletContext.getResourceAsStream(“WEB-INF/resources/yourfilename.cnf”) will return a nul exception, so be careful !

Happy coding.

Entry Filed under: english publications, java. Mots-clefs: , , , , , .

4 Comments Add your own

  • 1. Jan Ole  |  novembre 30, 2008 at 8:49

    Hi. I have great use of this article, but do you know how to, or if it is possible, to write to a file in the jar whitout unpacking and packing again?

    Répondre
  • 2. Amit  |  février 24, 2009 at 10:18

    it was really helpful and simple.Thanks.

    Répondre
    • 3. Radhesh  |  octobre 7, 2009 at 11:11

      it was of decent help..
      thanks..

      Répondre
  • 4. Radhesh  |  octobre 7, 2009 at 11:11

    It was of decent help to me too..
    thanks

    Répondre

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Catégories

Articles récents

Mots-clefs

2.0 java blogosphère admin apache configuration CSS debian desactiver desinstaller démons ECMAScript fluxbb forum gpg GWT httpd.conf IDE IM inetd install installer php+mysql inutiles iphone iphoneOS jabber java javamail Javascript kopete mysql ménage netbeans new Function php phpbb privacité pstree punbb remove daemon serveur dédié services services linux sujet tomcat utf8 xinetd

Méta

Articles les plus consultés