2

I'm trying to extract 2 jar files from the currently running jar however they always end up at 2kb even though their sizes are 104kb and 1.7m, Heres what I've got

public static boolean extractFromJar(String fileName, String dest) {
    if (Configuration.getRunningJarPath() == null) {
        return false;
    }
    File file = new File(dest + fileName);
    if (file.exists()) {
        return false;
    }

    if (file.isDirectory()) {
        file.mkdir();
        return false;
    }
    try {
        JarFile jar = new JarFile(Configuration.getRunningJarPath());
        Enumeration<JarEntry> e = jar.entries();
        while (e.hasMoreElements()) {
            JarEntry je = e.nextElement();
            InputStream in = new BufferedInputStream(jar.getInputStream(je));
            OutputStream out = new BufferedOutputStream(
                    new FileOutputStream(file));
            copyInputStream(in, out);
        }
        return true;
    } catch (Exception e) {
        Methods.debug(e);
        return false;
    }
}

private final static void copyInputStream(InputStream in, OutputStream out)
        throws IOException {
    while (in.available() > 0) {
        out.write(in.read());
    }
    out.flush();
    out.close();
    in.close();
}
tshepang
  • 12,111
  • 21
  • 91
  • 136
Matt Langlois
  • 305
  • 3
  • 17

3 Answers3

2

This should work better then relying on InputStream.available() method:

private final static void copyInputStream(InputStream in, OutputStream out)
        throws IOException {
    byte[] buff = new byte[4096];
    int n;
    while ((n = in.read(buff)) > 0) {
        out.write(buff, 0, n);
    }
    out.flush();
    out.close();
    in.close();
}
Eugene Kuleshov
  • 31,461
  • 5
  • 66
  • 67
1

available() method is not reliable to read data as it is just an estimate, as per its documentation.
You need to depend on read() method until read a non -ve.

byte[] contentBytes = new byte[ 4096 ];  
int bytesRead = -1;
while ( ( bytesRead = inputStream.read( contentBytes ) ) > 0 )   
{   
    out.write( contentBytes, 0, bytesRead );  
} // while available

You can go through a discussion on what the problems with available() is at here.

Community
  • 1
  • 1
Ravinder Reddy
  • 23,692
  • 6
  • 52
  • 82
0

I'm not sure about extracting jars, but every jar is actually a zip file, so you can try unzip it.

you can findout about unziping in java here: How to unzip files recursively in Java?

Community
  • 1
  • 1
Elimicky
  • 31
  • 3