Reputation: 342
i want to unzip all the folders and different kind of files like .xls,.apk,.png etc.But while extracting all the files are their in newly extracted foder(or folders under that folder). but those .xml,.png ,.apk files are not in proper format. when i open ,xls file it shows a pop that format may be different and also when it opens that files all the content is in different format. .png files are also not able to open, neither .apk are useful after extracting. why it is happening ?? **
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class UnzipFiles {
public static void main(String a[]){
UnzipFiles mfe = new UnzipFiles();
mfe.unzipFile("E:/New folder/pics.zip");
}
public void unzipFile(String filePath){
FileInputStream fis = null;
ZipInputStream zipIs = null;
ZipEntry zEntry = null;
try {
fis = new FileInputStream(filePath);
zipIs = new ZipInputStream(new BufferedInputStream(fis));
while((zEntry = zipIs.getNextEntry()) != null){
try{
byte[] tmp = new byte[25*1024*1024];
FileOutputStream fos = null;
/*String opFilePath = "E:/New folder/new/"+zEntry.getName();*/
String opFilePath= "E:/New folder/new"+File.separator+zEntry.getName();
File f = new File( opFilePath);
if(zEntry.isDirectory())
{ f.mkdirs();
System.out.println(f.getName()+" "+"folder created");
}
else{
System.out.println(f.getName());
/*System.out.println("Extracting file to "+opFilePath);*/
fos = new FileOutputStream(f);
BufferedOutputStream out = new BufferedOutputStream(fos);
int size = 0;
int k= zipIs.read(tmp);
System.out.println(k+1);
while((size = zipIs.read(tmp)) != -1){
out.write(tmp, 0 , size);
}
}
} catch(Exception ex){
ex.printStackTrace();
}
}
zipIs.closeEntry();
zipIs.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException exc) {
// TODO Auto-generated catch block
exc.printStackTrace();
}
}
}
**
Upvotes: 0
Views: 360
Reputation: 121692
You forget to put the first bytes you read into the destination file:
int k= zipIs.read(tmp); // <--- HERE
System.out.println(k+1);
while((size = zipIs.read(tmp)) != -1){
out.write(tmp, 0 , size);
Also, if you use Java 7, use a ZIP FileSystem
instead, along with Files.walkFileTree()
; that will make your job much more simple!
Upvotes: 2