|
| 1 | +package com.hmkcode; |
| 2 | + |
| 3 | +import java.io.File; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.io.FileNotFoundException; |
| 6 | +import java.io.FileOutputStream; |
| 7 | +import java.io.IOException; |
| 8 | +import java.util.zip.ZipEntry; |
| 9 | +import java.util.zip.ZipInputStream; |
| 10 | + |
| 11 | +public class Unzip { |
| 12 | + |
| 13 | + public static void unzip(String zipFile,String outputPath){ |
| 14 | + |
| 15 | + if(outputPath == null) |
| 16 | + outputPath = ""; |
| 17 | + else |
| 18 | + outputPath+=File.separator; |
| 19 | + |
| 20 | + // 1.0 Create output directory |
| 21 | + File outputDirectory = new File(outputPath); |
| 22 | + |
| 23 | + if(outputDirectory.exists()) |
| 24 | + outputDirectory.delete(); |
| 25 | + |
| 26 | + outputDirectory.mkdir(); |
| 27 | + |
| 28 | + |
| 29 | + // 2.0 Unzip (create folders & copy files) |
| 30 | + try { |
| 31 | + |
| 32 | + // 2.1 Get zip input stream |
| 33 | + ZipInputStream zip = new ZipInputStream(new FileInputStream(zipFile)); |
| 34 | + |
| 35 | + ZipEntry entry = null; |
| 36 | + int len; |
| 37 | + byte[] buffer = new byte[1024]; |
| 38 | + |
| 39 | + // 2.2 Go over each entry "file/folder" in zip file |
| 40 | + while((entry = zip.getNextEntry()) != null){ |
| 41 | + |
| 42 | + if(!entry.isDirectory()){ |
| 43 | + System.out.println("-"+entry.getName()); |
| 44 | + |
| 45 | + // create a new file |
| 46 | + File file = new File(outputPath +entry.getName()); |
| 47 | + |
| 48 | + // create file parent directory if does not exist |
| 49 | + if(!new File(file.getParent()).exists()) |
| 50 | + new File(file.getParent()).mkdirs(); |
| 51 | + |
| 52 | + // get new file output stream |
| 53 | + FileOutputStream fos = new FileOutputStream(file); |
| 54 | + |
| 55 | + // copy bytes |
| 56 | + while ((len = zip.read(buffer)) > 0) { |
| 57 | + fos.write(buffer, 0, len); |
| 58 | + } |
| 59 | + |
| 60 | + fos.close(); |
| 61 | + } |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | + }catch (FileNotFoundException e) { |
| 66 | + e.printStackTrace(); |
| 67 | + } catch (IOException e) { |
| 68 | + e.printStackTrace(); |
| 69 | + } |
| 70 | + } |
| 71 | +} |
0 commit comments