i have a java service that take a byte array in order to convert it in one or more pdf files or jpg files. i know this service work because it's called from another java system that correctly send files with no problems. now i need to call this services from a angular js system, the byte array, once reached the java application, it's converted first to a ByteArrayInputStream with not problems then the ByteArrayInputStream it's converted to ZipInputStream but fail. i suspect the problem is the type of encoding of the array.
This is my code:
public static Hashtable<String, ByteArrayOutputStream> unzipFile(InputStream inputStream){
logger.info("Unzip del File");
Hashtable<String, ByteArrayOutputStream> fileOutputTable = new Hashtable<String, ByteArrayOutputStream>();
try{
byte[] buf = new byte[1024];
ZipEntry zipentry;
ByteArrayInputStream bis = (ByteArrayInputStream)inputStream;
ZipInputStream zipinputstream = new ZipInputStream(bis); // here conversion fail
while((zipentry = zipinputstream.getNextEntry()) != null){
String entryName = zipentry.getName();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = 0;
while((n = zipinputstream.read(buf, 0, 1024)) > -1)
baos.write(buf, 0, n);
baos.close();
fileOutputTable.put(entryName, baos);
zipinputstream.closeEntry();
}
zipinputstream.close();
}catch(Exception e){
logger.error("Errore nel tentativo di unzip del file");
e.printStackTrace();
}
logger.info("RETURN: " + fileOutputTable.toString());
return fileOutputTable;
}
public static Hashtable<String, ByteArrayOutputStream> unzipFile(InputStream inputStream){
logger.info("Unzip del File");
Hashtable<String, ByteArrayOutputStream> fileOutputTable = new Hashtable<String, ByteArrayOutputStream>();
try{
byte[] buf = new byte[1024];
ZipEntry zipentry;
ByteArrayInputStream bis = (ByteArrayInputStream)inputStream;
ZipInputStream zipinputstream = new ZipInputStream(bis); // here conversion fail
while((zipentry = zipinputstream.getNextEntry()) != null){
String entryName = zipentry.getName();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int n = 0;
while((n = zipinputstream.read(buf, 0, 1024)) > -1)
baos.write(buf, 0, n);
baos.close();
fileOutputTable.put(entryName, baos);
zipinputstream.closeEntry();
}
zipinputstream.close();
}catch(Exception e){
logger.error("Errore nel tentativo di unzip del file");
e.printStackTrace();
}
logger.info("RETURN: " + fileOutputTable.toString());
return fileOutputTable;
}
Related
I am getting blank zip even though I am writing images to it .Can some one let me know what I am doing wrong?I am trying to add images to the zip file .Its creating a zip file but with blank entry on it .so why its not writing the file to it?
int i = 0;
List<String> filenames = new ArrayList<String>();
for (Iterator iterator = datas.iterator(); iterator.hasNext();) {
byte[] bs = (byte[]) iterator.next();
BufferedImage image = null;
ByteArrayInputStream bis = new ByteArrayInputStream(bs);
image = ImageIO.read(bis);
bis.close();
// write the image to a file
File outputfile = new File("image" + i + ".jpg");
System.out.println("*************************" + outputfile.getAbsolutePath());
ImageIO.write(image, "jpg", outputfile);
i++;
filenames.add(outputfile.getAbsolutePath());
}
// Create the ZIP file
//create object of FileOutputStream
FileOutputStream fout = new FileOutputStream(zipName);
//create object of ZipOutputStream from FileOutputStream
ZipOutputStream zout = new ZipOutputStream(fout);
byte[] buffer = new byte[2048];
for (int k = 0; k < filenames.size(); k++) {
FileInputStream fis = new FileInputStream(filenames.get(k).toString());
// Add ZIP entry to output stream.
File file = new File(filenames.get(k).toString());
String entryname = file.getName();
zout.putNextEntry(new ZipEntry(entryname));
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
zout.write(buffer, 0, bytesRead);
}
zout.closeEntry();
fis.close();
}
zout.flush();
fout.flush();
zout.close();
fout.close();
I have the following java method which I'm trying to use to create a zip file, which has an existing file written into it (the zip file has the same name, just with the .log extension replaced with .zip) . The zip file is created successfully, however the file is not inside it when it completes.
Here is my code:
private static void zipFile(File fileToZip) {
final int bufferSize = 2048;
File zipFile = new File(fileToZip.getAbsolutePath().replaceAll(".log", ".zip"));
try (FileOutputStream fos = new FileOutputStream(zipFile.getAbsolutePath());
FileInputStream fis = new FileInputStream(fileToZip);
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(fos));
BufferedInputStream origin = new BufferedInputStream(fis, bufferSize)) {
ZipEntry ze = new ZipEntry(fileToZip.getAbsolutePath());
zos.putNextEntry(ze);
byte[] data = new byte[bufferSize];
int count;
while ((count = origin.read(data, 0, bufferSize)) != -1) {
LOGGER.info("WRITING!!!");
zos.write(data, 0, count);
}
zos.closeEntry();
} catch (IOException e) {
LOGGER.error("Error: ", e);
}
}
Any ideas? :)
Change
ZipEntry ze = new ZipEntry(fileToZip.getAbsolutePath());
to
ZipEntry ze = new ZipEntry(fileToZip.getName());
My file unzips one folder and one file but does not unzip the rest for some reason. How can I make it so it unzips all of the zip files contents?
public void unzip(String filepath, String filename, String unzip_path) throws IOException {
InputStream is = new FileInputStream(filepath + filename);
Log.d("1st", filepath + filename);
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
try {
ZipEntry ze;
while ((ze = zis.getNextEntry()) != null) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int count;
String filename_temp = ze.getName();
File fmd = new File(unzip_path + filename_temp);
Log.d("2nd", unzip_path + filename_temp);
if (!fmd.getParentFile().exists()) {
fmd.getParentFile().mkdirs();
}
FileOutputStream fout = new FileOutputStream(unzip_path + filename_temp);
while ((count = zis.read(buffer)) != -1) {
baos.write(buffer, 0, count);
byte[] bytes = baos.toByteArray();
fout.write(bytes);
baos.reset();
}
fout.close();
//}
}
} finally {
zis.close();
}
}
I am trying to convert an array of bytes into a ZIP file. I got bytes using the following code:
byte[] originalContentBytes= new Verification().readBytesFromAFile(new File("E://file.zip"));
private byte[] readBytesFromAFile(File file) {
int start = 0;
int length = 1024;
int offset = -1;
byte[] buffer = new byte[length];
try {
//convert the file content into a byte array
FileInputStream fileInuptStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(
fileInuptStream);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((offset = bufferedInputStream.read(buffer, start, length)) != -1) {
byteArrayOutputStream.write(buffer, start, offset);
}
bufferedInputStream.close();
byteArrayOutputStream.flush();
buffer = byteArrayOutputStream.toByteArray();
byteArrayOutputStream.close();
} catch (FileNotFoundException fileNotFoundException) {
fileNotFoundException.printStackTrace();
} catch (IOException ioException) {
ioException.printStackTrace();
}
return buffer;
}
But my problem now is with converting the byte array back into a ZIP file - how can it be done?
Note : The specified ZIP contains two files.
To get the contents from the bytes you can use
ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(bytes));
ZipEntry entry = null;
while ((entry = zipStream.getNextEntry()) != null) {
String entryName = entry.getName();
FileOutputStream out = new FileOutputStream(entryName);
byte[] byteBuff = new byte[4096];
int bytesRead = 0;
while ((bytesRead = zipStream.read(byteBuff)) != -1)
{
out.write(byteBuff, 0, bytesRead);
}
out.close();
zipStream.closeEntry();
}
zipStream.close();
You probably are looking for code like this:
ZipInputStream z = new ZipInputStream(new ByteArrayInputStream(buffer))
now you can get the zip file contents via getNextEntry()
Here is a helper method
private fun getZipData(): ByteArray {
val zipFile: File = getTempZipFile() // Return a zip File
val encoded = Files.readAllBytes(Paths.get(zipFile.absolutePath))
zipFile.delete() // If you wish to delete the zip file
return encoded
}
I have retrieved a zip entry from a zip file like so.
InputStream input = params[0];
ZipInputStream zis = new ZipInputStream(input);
ZipEntry entry;
try {
while ((entry = zis.getNextEntry())!= null) {
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This works fine and its getting my ZipEntry no problem.
My Question
How can I get the contents of these ZipEntries into a String as they are xml and csv files.
you have to read from the ZipInputStream:
StringBuilder s = new StringBuilder();
byte[] buffer = new byte[1024];
int read = 0;
ZipEntry entry;
while ((entry = zis.getNextEntry())!= null) {
while ((read = zis.read(buffer, 0, 1024)) >= 0) {
s.append(new String(buffer, 0, read));
}
}
When you exit from the inner while save the StringBuilder content, and reset it.
With defined encoding (e.g. UTF-8) and without creation of Strings:
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
import java.io.ByteArrayOutputStream;
import static java.nio.charset.StandardCharsets.UTF_8;
try (
ZipInputStream zis = new ZipInputStream(input, UTF_8);
ByteArrayOutputStream baos = new ByteArrayOutputStream()
) {
byte[] buffer = new byte[1024];
int read = 0;
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null)
while ((read = zis.read(buffer, 0, buffer.length)) > 0)
baos.write(buffer, 0, read);
String content = baos.toString(UTF_8.name());
}
Here is the approach, which does not break Unicode characters:
final ZipInputStream zis = new ZipInputStream(new ByteArrayInputStream(content));
final InputStreamReader isr = new InputStreamReader(zis);
final StringBuilder sb = new StringBuilder();
final char[] buffer = new char[1024];
while (isr.read(buffer, 0, buffer.length) != -1) {
sb.append(new String(buffer));
}
System.out.println(sb.toString());
I would use apache's IOUtils
ZipEntry entry;
InputStream input = params[0];
ZipInputStream zis = new ZipInputStream(input);
try {
while ((entry = zis.getNextEntry())!= null) {
String entryAsString = IOUtils.toString(zis, StandardCharsets.UTF_8);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
IOUtils.closeQuietly(zis);
Kotlin version but can be used in Java as well
val zipInputStream = ZipInputStream(inStream)
var zipEntry = zipInputStream.nextEntry
while(zipEntry != null) {
println("Name of file : " + zipEntry.name)
val fileContent = String(zipInputStream.readAllBytes(), StandardCharsets.UTF_8)
println("File content : $fileContent")
zipEntry = zipInputStream.nextEntry
}