Created
December 21, 2016 16:19
-
-
Save viet-wego/b767756dd1abea4fec98cb94859c3634 to your computer and use it in GitHub Desktop.
Sample java code to unzip a file to current directory.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.github.viettd.how.to; | |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.io.FileOutputStream; | |
import java.util.ArrayList; | |
import java.util.Collections; | |
import java.util.List; | |
import java.util.zip.ZipEntry; | |
import java.util.zip.ZipInputStream; | |
public class Unziper { | |
private static final String INPUT_FILE = "/home/viettd/java-how-to/java-how-to.zip"; | |
public static void main(String[] args) { | |
unzip(INPUT_FILE); | |
} | |
public static List<String> unzip(String zipFilePath) { | |
try { | |
File zipFile = new File(zipFilePath); | |
try (ZipInputStream inputStream = new ZipInputStream(new FileInputStream(zipFile))) { | |
List<String> fileList = new ArrayList<>(); | |
ZipEntry entry = inputStream.getNextEntry(); | |
while (entry != null) { | |
File newFile = new File(zipFile.getParent() + File.separator + entry.getName()); | |
new File(newFile.getParent()).mkdirs(); | |
if (!entry.isDirectory()) { | |
try (FileOutputStream outputStream = new FileOutputStream(newFile)) { | |
int length; | |
byte[] buffer = new byte[1024]; | |
while ((length = inputStream.read(buffer)) > 0) { | |
outputStream.write(buffer, 0, length); | |
} | |
} | |
} | |
fileList.add(newFile.getAbsolutePath()); | |
entry = inputStream.getNextEntry(); | |
} | |
inputStream.closeEntry(); | |
return fileList; | |
} | |
} catch (Exception e) { | |
System.out.println(String.format("unzip error: %s", e)); | |
return Collections.emptyList(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment