Set filename of an only streamed zip file - java

i am currently creating a zip file and filling it with various json files and images. All this should only run in memory and not on the hard disk. Therefore I have the following construct so far:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zip = null;
String FILE_NAME = "file.zip";
try {
zip = new ZipOutputStream(baos);
//now the critical part where the name of the file should be set
ZipEntry entry = new ZipEntry(FILE_NAME);
zip.putNextEntry(entry);
byte[] data = FILE_NAME.getBytes();
zip.write(data, 0, data.length);
zip.closeEntry();
//end of critical part and filling the rest of the zip
//...
//
}finally{
IOUtils.closeQuietly(zip);
byte[] byteFile = baos.toByteArray();
IOUtils.closeQuietly(baos);}
The problem is that the zip-file is called file.zip, but also contains a file.zip itself.
How can I name my Zip file from the ZipOutputStream without packing into this one file with the same name? Unfortunately I only found this solution here.

public byte[] zipBytesFile(List<byte[]> files) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
int i = 0;
for (byte[] file : files) {
ZipEntry entry = new ZipEntry(++i + ".pdf");
entry.setSize(file.length);
zos.putNextEntry(entry);
zos.write(file);
}
zos.closeEntry();
zos.close();
return baos.toByteArray();
}

Related

Split big zip file and combine it back as original zip file

I have a requirement to split a 100mb zip file(which will be having sub folders and images) into 10 zip files(each of 10mb).Then I need to send each sliced zip files to an API (as multipart reauest), in receiver API i need to combine each of the above 10 zip files back to origin 100mb zip file.
Below is the code for slicing
public static void splitZip(String zipName, String location, String NewZip) throws IOException{
FileInputStream fis = new FileInputStream(location);
ZipInputStream zipInputStream = new ZipInputStream(fis);
ZipEntry entry = null;
int currentChunkIndex = 0;
long entrySize = 0;
ZipFile zipFile = new ZipFile(location);
Enumeration enumeration = zipFile.entries();
String copDest = zipCopyDest + "\\" + NewZip + "_" + currentChunkIndex +".zip";
FileOutputStream fos = new FileOutputStream(new File(copDest));
BufferedOutputStream bos = new BufferedOutputStream(fos);
ZipOutputStream zos = new ZipOutputStream(bos);
long currentSize = 0;
try {
while ((entry = zipInputStream.getNextEntry()) != null && enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
System.out.println(zipEntry.getName());
System.out.println(zipEntry.getSize());
entrySize = zipEntry.getSize();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
if((currentSize + entrySize) > MAX_FILE_SIZE) {
zos.close();
currentChunkIndex++;
zos = getOutputStream(currentChunkIndex, NewZip);
currentSize = 0;
}else{
currentSize += entrySize;
zos.putNextEntry(new ZipEntry(entry.getName()));
byte[] buffer = new byte[8192];
int length = 0;
while ((length = zipInputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, length);
}
byte[] unzippedFile = outputStream.toByteArray();
zos.write(unzippedFile);
unzippedFile = null;
outputStream.close();
zos.closeEntry();
}
}
} finally {
zos.close();
}
}
When i extract slices zips manually i found some images are corrupted am not able to open it. Also am not getting a proper solution for combining the zip files. Thanks in advance.
Zip specification has a feature to split zip files to any desired length (minimum split length should be 64kb). Zip4j, supports this feature to create split zip files (documentation). You can then pass each split file to the api. The api can then use the merge functionality in zip4j to merge those split files into a single zip file. On a side note: even without merging, it is a perfectly valid zip file. as long as all the split zip files are in the same directory.
The approach will not work if you have any file in the zip greater than 10 mb and also the else condition should be executed in both the cases and in this approach you have to depend on the size of file in zip may be better you go with approach of not creating smaller zips

Amazon Merchant Fulfilment Create Shipment Label

I am trying to get the shipment label from amazon merchant fulfillment as per the instructions mentioned on the Amazon pages.
"To obtain the actual PDF document, you must decode the Base64-encoded string, save it as a binary file with a “.zip” extension, and then extract the PDF file from the ZIP file."
Has any one got it to work. I have tried couple of things but every time i get blank pdf.
Here is my code. Can please some body guide me if I am doing it correctly
byte[] decodedBytes = Base64.decodeBase64(contents);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("c:\\output\\asdwd.zip")));
//now create the entry in zip file
ZipEntry entry = new ZipEntry("asd.pdf");
zos.putNextEntry(entry);
zos.write(decodedBytes);
zos.close();
The instructions say to save the bytes as a binary file with the extension .zip.
What you are actually doing is creating a ZIP file with the contents of the byte array as an entry.
According to my reading of the instructions, your code should do this:
byte[] decodedBytes = Base64.decodeBase64(contents);
FileOutputStream fos = new FileOutputStream("c:\\output\\asdwd.zip");
fos.write(decodedBytes);
fos.close();
Or better still:
byte[] decodedBytes = Base64.decodeBase64(contents);
try (FileOutputStream fos = new FileOutputStream("c:\\output\\asdwd.zip")) {
fos.write(decodedBytes);
}
Then using a ZIP tool or a web browser, open asdwd.zip, find the entry containing the PDF, and extract it or print it.
Here is the code to generate a shipping label in case somebody needs it.
byte[] decoded = Base64.decodeBase64(contents);
try (FileOutputStream fos = new FileOutputStream(zipFilePath + amazonOrderId + zipFileName)) {
fos.write(decoded);
fos.close();
}
file = new File(destDirectory + amazonOrderId + pngFile);
if (file.exists()) {
file.delete();
}
try (OutputStream out = new FileOutputStream(destDirectory + amazonOrderId + pngFile)) {
try (InputStream in = new GZIPInputStream(
new FileInputStream(zipFilePath + amazonOrderId + zipFileName))) {
byte[] buffer = new byte[65536];
int noRead;
while ((noRead = in.read(buffer)) != -1) {
out.write(buffer, 0, noRead);
}
}
}

java create NESTED zip recursively in memory

This is how I create a simple zip archive with 3 files
FileOutputStream fos = new FileOutputStream(new File("out.zip"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
for (int i = 0; i < 3; i++) {
String s = "hello world " + i;
ZipEntry entry = new ZipEntry("text" + i + ".txt");
zos.putNextEntry(entry);
zos.write(s.getBytes());
zos.closeEntry();
}
}
baos.writeTo(fos);
How can I put a zip inside zip recursively in one turn on the fly? Is there any way to put ZipOutputStream or ZipEntry inside each other?
EDIT:
Solution as Mark suggested:
FileOutputStream fos = new FileOutputStream(new File("out.zip"));
ByteArrayOutputStream resultBytes = new ByteArrayOutputStream();
ByteArrayOutputStream zipOutStream = new ByteArrayOutputStream();
try (ZipOutputStream zos2 = new ZipOutputStream(zipOutStream)) {
String s = "hello world ";
ZipEntry entry = new ZipEntry("text.txt");
zos2.putNextEntry(entry);
zos2.write(s.getBytes());
zos2.closeEntry();
zos2.close();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (ZipOutputStream zos = new ZipOutputStream(baos)) {
ZipEntry entry = new ZipEntry("text.zip");
zos.putNextEntry(entry);
zos.write(zipOutStream.toByteArray());
zos.closeEntry();
}
baos.writeTo(resultBytes);
resultBytes.writeTo(fos);
I tried to follow the solution using the 'ByteArrayOutputStream' but only manage to create corrupted zip files this way.
I ended up creating a nested ZipOutputStream directly like this:
try (FileOutputStream fos = new FileOutputStream(myZipFile); ZipOutputStream zos = new ZipOutputStream(fos)) {
ZipEntry entry = new ZipEntry("inner.zip");
zos.putNextEntry(entry);
ZipOutputStream nestedZos = new ZipOutputStream(zos);
// write stuff to nestedZos
nestedZos.finish();
zos.closeEntry();
}
The resulting zip file contains the nested structure and is valid.
For the "inner" .ZIP file, you could use a ByteArrayOutputStream instead of a FileOutputStream; then that zip will be built as data in RAM; so you can use the resulting byte array as the data for a ZipEntry in the outer .ZIP file.

Zip Jasper reports [duplicate]

I am trying to create a zip file of multiple image files. I have succeeded in creating the zip file of all the images but somehow all the images have been hanged to 950 bytes. I don't know whats going wrong here and now I can't open the images were compressed into that zip file.
Here is my code. Can anyone let me know what's going here?
String path="c:\\windows\\twain32";
File f=new File(path);
f.mkdir();
File x=new File("e:\\test");
x.mkdir();
byte []b;
String zipFile="e:\\test\\test.zip";
FileOutputStream fout=new FileOutputStream(zipFile);
ZipOutputStream zout=new ZipOutputStream(new BufferedOutputStream(fout));
File []s=f.listFiles();
for(int i=0;i<s.length;i++)
{
b=new byte[(int)s[i].length()];
FileInputStream fin=new FileInputStream(s[i]);
zout.putNextEntry(new ZipEntry(s[i].getName()));
int length;
while((length=fin.read())>0)
{
zout.write(b,0,length);
}
zout.closeEntry();
fin.close();
}
zout.close();
This is my zip function I always use for any file structures:
public static File zip(List<File> files, String filename) {
File zipfile = new File(filename);
// Create a buffer for reading the files
byte[] buf = new byte[1024];
try {
// create the ZIP file
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipfile));
// compress the files
for(int i=0; i<files.size(); i++) {
FileInputStream in = new FileInputStream(files.get(i).getCanonicalName());
// add ZIP entry to output stream
out.putNextEntry(new ZipEntry(files.get(i).getName()));
// transfer bytes from the file to the ZIP file
int len;
while((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
// complete the entry
out.closeEntry();
in.close();
}
// complete the ZIP file
out.close();
return zipfile;
} catch (IOException ex) {
System.err.println(ex.getMessage());
}
return null;
}
Change this:
while((length=fin.read())>0)
to this:
while((length=fin.read(b, 0, 1024))>0)
And set buffer size to 1024 bytes:
b=new byte[1024];

Zipping files with ZipOutputStream gives inconsistent results

I want to zip a text file using the java.util.ZipOutputStream class. I found two examples on the internet explaining on how to do that. This led me to the two possible implementations shown below. While both methods produce 'healthy zip files', my problem is that on every run the binary content of the file is slightly different (around the 10th byte). Does someone know if
This is intended behaviour
There is a way to always produce exactly the same result
Here is my current code:
public byte[] getZipByteArray(String fileName) throws IOException
{
byte[] result = new byte[0];
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
ZipEntry ze = new ZipEntry(fileName);
zos.putNextEntry(ze);
InputStream inputStream = ZipCompression.class.getResourceAsStream(fileName);
int len;
while ((len = inputStream.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
zos.closeEntry();
zos.close();
result = baos.toByteArray();
return result;
}
public byte[] ZipByteArrayBuffered(String fileName) throws IOException
{
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream);
ZipOutputStream zipOutputStream = new ZipOutputStream(bufferedOutputStream);
File file = new File(fileName);
InputStream fileInputStream = ZipCompression.class.getResourceAsStream(file.getName());
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
IOUtils.copy(fileInputStream, zipOutputStream);
fileInputStream.close();
zipOutputStream.closeEntry();
if (zipOutputStream != null)
{
zipOutputStream.finish();
zipOutputStream.flush();
IOUtils.closeQuietly(zipOutputStream);
}
IOUtils.closeQuietly(bufferedOutputStream);
IOUtils.closeQuietly(byteArrayOutputStream);
return byteArrayOutputStream.toByteArray();
}
Byte 10 starts the file modification date and so this will always differ. See Wikipedia for the details of the zip file format.

Categories

Resources