0

I am trying to copy a file (Base.jar) to the same directory as the running jar file I keep getting a corrupted jar file, that still holds the correct class structure when opened with winrar. What am I doing wrong? (I have also tried without the ZipInputStream, but that was no help) the byte[] is 20480 because that is size of it on the disk.

my code:

private static void getBaseFile() throws IOException 
{
    InputStream input = Resource.class.getResourceAsStream("Base.jar");
    ZipInputStream zis = new ZipInputStream(input);
    byte[] b = new byte[20480];
    try {
        zis.read(b);
    } catch (IOException e) {
    }
    File dest = new File("Base.jar");
    FileOutputStream fos = new FileOutputStream(dest);
    fos.write(b);
    fos.close();
    input.close();
}
  • Have you tried doing a byte-for-byte comparison of the files? If I had to guess, I suspect you're trimming bytes off the end of your file. – Gian Jul 06 '13 at 02:01

4 Answers4

0
InputStream input = Resource.class.getResourceAsStream("Base.jar");

File fileOut = new File("your lib path");

OutputStream out = FileUtils.openOutputStream(fileOut);
IOUtils.copy(in, out);
in.close();
out.close();

and handle exceptions

jmj
  • 237,923
  • 42
  • 401
  • 438
0

No need to use ZipInputStream, unless you want to unzip the contents into memory and read. Just use BufferedInputStream(InputStream) or BufferedReader(InputStreamReader(InputStream)).

Glen Best
  • 22,769
  • 3
  • 58
  • 74
0

did some more googling found this: (Convert InputStream to byte array in Java) worked for me

InputStream is = ...
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
byte[] data = new byte[16384];
while ((nRead = is.read(data, 0, data.length)) != -1) {
    buffer.write(data, 0, nRead);
}
buffer.flush(); 
return buffer.toByteArray();

(it looks very simular to the src for IOUtils.copy())

Community
  • 1
  • 1
0

ZipInputStream is for reading files in the ZIP file format by entry. You need to copy the whole file (resource) that is you need to simply copy all bytes from InputStream no matter what format is. The best way to do it in Java 7 is this:

Files.copy(inputStream, targetPath, optionalCopyOptions);

see API for details

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275