Posts

Showing posts from August, 2011

Accessing a file in a jar using java.io.File

Obtaining links to files in jars is possible through 2 different method calls:
getClass().getResource(String name);
getClass().getResourceAsStream(String name);

The first method will return a URL to the file which won't be of any good to the java.io.File class.
The second method will return an InputStream object to that file, which we will use.

java.io.File doesn't access files using InputStreams nor any File class that I know about. So we will have to create a file using the InputStream, then obtain a URL to it, then use java.io.File to obtain a reference to that file.

Check the following method:

public void copyStreams(InputStream in, OutputStream out, int buffersize)
     throws IOException
   {
     byte[] bytes = new byte[buffersize];
     int bytesRead = in.read(bytes);
     while (bytesRead > -1) {
       out.write(bytes, 0, bytesRead);
       bytesRead = in.read(bytes);
     }
}
//I borrowed this method from a library I'm using, but it's working fine. The default bu…

How to create a JAR using Eclipse and use it in one of your projects

Image
This post shows how to create a jar containing resources for other projects withing eclipse in particular. It will surely work with java projects developed in other IDEs but I specifically mention something extra regarding this situation.

It's assumed that you have at least some idea how Apache Ant. And of course have it installed on your machine.

1. Create a java project.
2. Have your resources (i.e. classes, files...etc) created and built.
3. Add a build.xml file in your project folder containing the following text:
<project name="ipKaizenCore" basedir="." default="clean-build">
    <property name="src.dir"     value="src">
    <property name="classes.dir" value="bin">
    <property name="jar.dir"     value="build">
    <target name="clean">
        <delete dir="${jar.dir}">
    </target>
    <target name="compile"&g…