Unzip to internal storage not working completely - java

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();
}
}

Related

Java not writing to zip file

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());

Add files to a folder inside a zip that is inside a zip in Java

I have a zip file that contains a zip that includes folders to which I have to add some files. The structure is like
outerZip.zip
|folder
|innerZip.zip
|innerFolder
I need to add a few files to the inner folder.
I can return the innerZip ok, if I save it to file it shows the correct structure.
Now when I want to iterate through the ZipEntries of the innerZip for the first entry it shows to be /innerFolder, but when I want to add the entry content to the updated zip file it turns out that it contains data and throws the below error:
java.util.zip.ZipException: invalid entry CRC (expected 0x0 but got 0x46480bab)
at java.util.zip.ZipInputStream.read(ZipInputStream.java:218)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at zip.builder.InnerBuilder.addFilesToInnerZip(InnerBuilder.java:179)
at zip.builder.InnerBuilder.addFilesToZip(InnerBuilder.java:117)
The code is here:
private byte[] addFilesToZip(byte[] outerZipBytes, Set<File> files) {
String zipPath = System.getProperty("catalina.home") + File.separator + "outerZipFile.zip";
File zipFile = new File(zipPath);
ZipFile outerZipFile = null;
try {
zipFile.createNewFile();
FileOutputStream fileout = new FileOutputStream(zipFile);
fileout.write(outerZipBytes);
fileout.close();
outerZipFile = new ZipFile(zipFile);
File innerZipFile = getInnerZipFile(outerZipFile);
addFilesToInnerZip(innerZipFile, files);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (outerZipFile != null)
outerZipFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// TODO convert updated outer zip file to byte array
return new byte[0];
}
private File getInnerZipFile(ZipFile outerZipFile) throws IOException {
String innerZipPath = System.getProperty("catalina.home") + File.separator + "innerZipFile.zip";
ZipEntry entry = outerZipFile.getEntry("folder/inner.zip");
InputStream innerZipInputStream = outerZipFile.getInputStream(entry);
FileOutputStream fout = new FileOutputStream(new File(innerZipPath));
byte[] buf = new byte[1024];
int data;
while ((data = innerZipInputStream.read(buf)) != -1) {
fout.write(buf, 0, data);
}
innerZipInputStream.close();
fout.close();
return new File(innerZipPath);
}
private void addFilesToInnerZip(File zipFile, Set<File> files) throws IOException {
File tempFile = File.createTempFile(zipFile.getName(), null);
tempFile.delete();
zipFile.renameTo(tempFile);
byte[] buf = new byte[1024];
ZipInputStream zin = new ZipInputStream(new FileInputStream(tempFile));
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
ZipEntry entry = zin.getNextEntry();
while (entry != null) {
// Add ZIP entry to output stream.
out.putNextEntry(new ZipEntry(entry.getName()));
// Transfer bytes from the ZIP file to the output file
int len;
while ((len = zin.read(buf)) > 0) { // line 179
out.write(buf, 0, len);
}
entry = zin.getNextEntry();
}
for (File file : files) {
InputStream in = new FileInputStream(file);
out.putNextEntry(new ZipEntry("innerFolder/"+ file.getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
zin.close();
out.close();
tempFile.delete();
}
Thanks for any help!

Java Download Zip from Webpage

I'm trying to download a zip file from a URL, and I have completed that. The problem is is that it keeps downloading the webpage itself, so I end up with some beautiful HTML, CSS, JS, and PHP. That's nowhere near a zip file.
Please correct me if I'm doing something wrong with my code:
private static String URL = "webpage/myzip.zip";
private static String OUTPUT_PATH = "path/to/extract/to";
private static File OUTPUT_DIRECTORY = new File(OUTPUT_PATH);
public static void create() throws Exception {
if (!OUTPUT_DIRECTORY.exists()) OUTPUT_DIRECTORY.mkdirs();
else return;
System.out.println("Natives not found. Downloading.");
BufferedInputStream in = null;
FileOutputStream fout = null;
try {
in = new BufferedInputStream(new URL(URL).openStream());
fout = new FileOutputStream(OUTPUT_PATH + File.separator + "myzip.zip");
final byte[] data = new byte[4096];
int count;
while ((count = in.read(data, 0, 1024)) != -1) {
fout.write(data, 0, count);
}
} finally {
if (in != null) in.close();
if (fout != null) fout.close();
}
OUTPUT_DIRECTORY = new File(OUTPUT_PATH);
File zip = OUTPUT_DIRECTORY.listFiles()[0];
ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zip));
ZipEntry ze = zipIn.getNextEntry();
byte[] buffer = new byte[4096];
while (ze != null) {
String fName = ze.getName();
File newFile = new File(OUTPUT_DIRECTORY + File.separator + fName);
new File(newFile.getParent()).mkdirs();
FileOutputStream fos = new FileOutputStream(newFile);
int len;
while ((len = zipIn.read(buffer)) > 0) {
fos.write(buffer, 0, len);
}
fos.close();
ze = zipIn.getNextEntry();
}
zipIn.closeEntry();
zipIn.close();
// zip.delete();
System.out.println("Natives Downloaded.");
}
Answer provided by: Scary Wombat
I didn't copy the link correctly. I was using a drop box link, and I forgot that I needed to copy the download link from when you hit the download button.

How to extract zip file which exist on the local machine to the partition on the server?

I have a zip file on the local machine in the C:\tem\test directory. I want to extract it on the server in the new directory which should have same name as zip file. how can i do it?
class UnZipFile {
final static File source = new File("C:\\tmp\\test\\R1112B2_BcfiHtm.zip");
public static void getZipFiles() {
try {
String destination ="U:\\root\\intranet\\res\\fi\\test";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(
new FileInputStream(source));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
//for each entry to be extracted
String entryName = zipentry.getName();
System.out.println("entryname " + entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if (directory == null) {
if (newFile.isDirectory())
break;
}
fileoutputstream = new FileOutputStream(
destination + entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1)
fileoutputstream.write(buf, 0, n);
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
I get following exception:
java.io.FileNotFoundException: C:\tmp\test\Attestn\1000100_FormDem_NS_NL.pdf (The system cannot find the path specified)

How to speed up unzipping time in Java / Android?

Unzipping files on android seems to be dreadfully slow. At first I thought this was just the emulator but it appears to be the same on the phone. I've tried different compression levels, and eventually dropped down to storage mode but it still takes ages.
Anyway, there must be a reason! Does anyone else have this problem? My unzip method looks like this:
public void unzip()
{
try{
FileInputStream fin = new FileInputStream(zipFile);
ZipInputStream zin = new ZipInputStream(fin);
File rootfolder = new File(directory);
rootfolder.mkdirs();
ZipEntry ze = null;
while ((ze = zin.getNextEntry())!=null){
if(ze.isDirectory()){
dirChecker(ze.getName());
}
else{
FileOutputStream fout = new FileOutputStream(directory+ze.getName());
for(int c = zin.read();c!=-1;c=zin.read()){
fout.write(c);
}
//Debug.out("Closing streams");
zin.closeEntry();
fout.close();
}
}
zin.close();
}
catch(Exception e){
//Debug.out("Error trying to unzip file " + zipFile);
}
}
I don't know if unzipping on Android is slow, but copying byte for byte in a loop is surely slowing it down even more. Try using BufferedInputStream and BufferedOutputStream - it might be a bit more complicated, but in my experience it is worth it in the end.
BufferedInputStream in = new BufferedInputStream(zin);
BufferedOutputStream out = new BufferedOutputStream(fout);
And then you can write with something like that:
byte b[] = new byte[1024];
int n;
while ((n = in.read(b,0,1024)) >= 0) {
out.write(b,0,n);
}
Thanks for the solution Robert.
I modified my unzip method and now it takes only a few seconds instead of 2 minutes.
Maybe someone's interested in my solution. So here you go:
public void unzip() {
try {
FileInputStream inputStream = new FileInputStream(filePath);
ZipInputStream zipStream = new ZipInputStream(inputStream);
ZipEntry zEntry = null;
while ((zEntry = zipStream.getNextEntry()) != null) {
Log.d("Unzip", "Unzipping " + zEntry.getName() + " at "
+ destination);
if (zEntry.isDirectory()) {
hanldeDirectory(zEntry.getName());
} else {
FileOutputStream fout = new FileOutputStream(
this.destination + "/" + zEntry.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zipStream.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
zipStream.closeEntry();
bufout.close();
fout.close();
}
}
zipStream.close();
Log.d("Unzip", "Unzipping complete. path : " + destination);
} catch (Exception e) {
Log.d("Unzip", "Unzipping failed");
e.printStackTrace();
}
}
public void hanldeDirectory(String dir) {
File f = new File(this.destination + dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
Using above ideas and ideas from some other sources I have created this class
Create this new class
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import android.util.Log;
public class DecompressFast {
private String _zipFile;
private String _location;
public DecompressFast(String zipFile, String location) {
_zipFile = zipFile;
_location = location;
_dirChecker("");
}
public void unzip() {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if(ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location + ze.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
bufout.close();
zin.closeEntry();
fout.close();
}
}
zin.close();
Log.d("Unzip", "Unzipping complete. path : " +_location );
} catch(Exception e) {
Log.e("Decompress", "unzip", e);
Log.d("Unzip", "Unzipping failed");
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if(!f.isDirectory()) {
f.mkdirs();
}
}
}
USAGE
just pass your file location of zip file and your destination Location to this class
example
String zipFile = Environment.getExternalStorageDirectory() + "/the_raven.zip"; //your zip file location
String unzipLocation = Environment.getExternalStorageDirectory() + "/unzippedtestNew/"; // unzip location
DecompressFast df= new DecompressFast(zipFile, unzipLocation);
df.unzip();
Dont Forget to add following permissions in manifest(also Run time permission if version higher than marshmellow)
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
hope this helps
The URL that helped me learn how to zip and unzip can be found here.
I used that URL in conjuction with user3203118's answer above for unzipping. This is for future references for people who run in to this issue and need help solving it.
Below is the ZipManager code I am using:
public class ZipManager {
private static final int BUFFER = 80000;
public void zip(String[] _files, String zipFileName) {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(zipFileName);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(
dest));
byte data[] = new byte[BUFFER];
for (int i = 0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].substring(_files[i]
.lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void unzip(String _zipFile, String _targetLocation) {
// create target location folder if not exist
dirChecker(_targetLocation);
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
// create dir if required while unzipping
if (ze.isDirectory()) {
dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(
_targetLocation + "/" + ze.getName());
BufferedOutputStream bufout = new BufferedOutputStream(fout);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
bufout.write(buffer, 0, read);
}
zin.closeEntry();
bufout.close();
fout.close();
}
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
private void dirChecker(String dir) {
File f = new File(dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
}
Just call this method and it will give you much better performance..
public boolean unzip(Context context) {
try {
FileInputStream fin = new FileInputStream(_zipFile);
ZipInputStream zin = new ZipInputStream(fin);
BufferedInputStream in = new BufferedInputStream(zin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
Log.v("Decompress", "Unzipping " + ze.getName());
if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location
+ ze.getName());
BufferedOutputStream out = new BufferedOutputStream(fout);
byte b[] = new byte[1024];
for (int c = in.read(b,0,1024); c != -1; c = in.read()) {
out.write(b,0,c);
}
zin.closeEntry();
fout.close();
}
}
zin.close();
return true;
} catch (Exception e) {
Log.e("Decompress", "unzip", e);
return false;
}
}
private void _dirChecker(String dir) {
File f = new File(_location + dir);
if (!f.isDirectory()) {
f.mkdirs();
}
}
In case of using BufferedOutputStream be sure to flush it. If you do not do it, size smaller than buffer will not be unzipped properly
if (ze.isDirectory()) {
_dirChecker(ze.getName());
} else {
FileOutputStream fout = new FileOutputStream(_location
+ ze.getName());
BufferedOutputStream out = new BufferedOutputStream(fout);
byte buffer[] = new byte[1024];
for (int c = in.read(buffer,0,1024); c != -1; c = in.read()) {
out.write(buffer,0,c);
}
out.flush();//flush it......
zin.closeEntry();
fout.close();
}

Categories