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 buffer size for this method was 4096

After creating a temp file. Obtain it's FileOutputStream (i.e. new FileOutputStream(File f)), then use the previous method by passing:

-InputStream from getResourceAsStream(String name)
-FileOutputStream
-And a buffer size of your choice

The last stem, is to tell me how did it go ? :)

Comments

Popular posts from this blog

Testing SOAP services using pingdom