i am trying to create a method which copies a java.io.File into a java.util.zip.ZipFile. For this i first open a java.util.zip.ZipOutputStream of the ZipFile, then create a new java.util.zip.ZipEntry with the name of the file, put that new ZipEntry in the ZipOutputStream and then write the content of the File to the ZipOutputStream. After that i flush the ZipOutputStream and close all streams.
For some reason i can't explain this procedure removes all other ZipEntries from the ZipFile and only leaves the copied one in there. Here is the code for copying the file (the file is represented by the java.io.InputStream parameter)
public static boolean compress(final InputStream pSourceStream, final ZipFile pTarget, final ZipEntry pContainer,
final String pFileName) {
if (pSourceStream != null && pTarget != null && pFileName != null && !pFileName.isEmpty()) {
try {
final ZipOutputStream output = new ZipOutputStream(new FileOutputStream(new File(pTarget.getName())));
final ZipEntry target = (pContainer != null) ? new ZipEntry(pContainer.getName() + pFileName)
: new ZipEntry(pFileName);
output.putNextEntry(target);
final byte[] buffer = new byte[BUFFER_SIZE];
int readBytes;
while ((readBytes = pSourceStream.read(buffer)) != -1) {
output.write(buffer, 0, readBytes);
}
pSourceStream.close();
output.flush();
output.close();
return true;
} catch (final IOException ignore) {
// took care of target
// ios will return false
}
}
return false;
}
Here is my code which calls this method
public static void main(final String[] args) throws ZipException, IOException {
final Package p = FileHandler.class.getPackage();
final InputStream classStream = FileHandler.stream(p, "FileHandler.class");
FileHandler.compress(classStream, new ZipFile(new File("C:/Users/litts/Desktop/FileHandlerTest/TestZip.jar")),
"FileHandler1.class");
}
So what im basicly doing here is copying the class-file of FileHandler to a zip-file. But all of its other content is removed when doing so.
You are not reading in the Zip file, you are just overwriting it at the file level.