In this article you will learn how to unzip file.
1. Read ZIP file with “
ZipInputStream”
2. Get the files to “
ZipEntry” and output it to “
FileOutputStream“
Decompress ZIP file exampleIn this example, it will read a ZIP file from
zipFile, and decompress all zipped files to
OUTPUT_FOLDER folder.
- public void unZipIt(String zipFile, String outputFolder){
-
byte[] buffer = new byte[1024];
-
-
try{
-
//create output directory is not exists
-
File folder = new File(OUTPUT_FOLDER);
-
if(!folder.exists()){
-
folder.mkdir();
-
}
-
//get the zip file content
-
ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));
-
//get the zipped file list entry
-
ZipEntry ze = zis.getNextEntry();
-
-
while(ze!=null){
-
String fileName = ze.getName();
-
File newFile = new File(outputFolder + File.separator +fileName);
-
System.out.println("file unzip: "+ newFile.getAbsoluteFile());
-
-
//create all non exists folders
-
//else you will hit FileNotFoundException for compressed folder
-
new File(newFile.getParent()).mkdirs();
-
-
FileOutputStream fos = new FileOutputStream(newFile);
-
-
int len;
-
while((len = zis.read(buffer)) > 0){
-
fos.write(buffer,0,len);
-
}
-
fos.close();
-
ze = zis.getNextEntry();
-
}
-
-
zis.closeEntry();
-
zis.close();
-
System.out.println("Extract completed.");
-
}catch(IOException e){
-
e.printStackTrace();
-
}
-
}
压缩解压完整实例:
阅读(2876) | 评论(0) | 转发(0) |