Skip to content

Instantly share code, notes, and snippets.

@naveenwashere
Created May 29, 2013 17:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save naveenwashere/5672237 to your computer and use it in GitHub Desktop.
Save naveenwashere/5672237 to your computer and use it in GitHub Desktop.
This is a simple class that decompresses any known archive file. You just have to provide the path of the file to decompress. I wrote this code as I saw a post in Google+ who wanted to know how to decompress a file. So I thought, "well, lets try to write one!". Though its a small code, I confess, I had to struggle a bit. Happy Coding.
package com.gplus;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Decompresser{
public static void main(String[] args) throws Exception {
int temp = 0;
System.out.println("Please enter the path of the Zip File along with the file name and file extension:");
Scanner in = new Scanner(System.in);
String fileName = in.nextLine();
ZipFile zipFile = new ZipFile(fileName);
int lastIndex = fileName.lastIndexOf(".");
int beginIndex = fileName.lastIndexOf("\\");
//Construct destination Dir for uncompressing the file
String destDir = new String((String) fileName.subSequence(0, beginIndex-1));
//Construct the destination file name
String destFileName = (String) fileName.subSequence(beginIndex, lastIndex);
//Create the uncompression Dir
new File(destDir + "\\" + destFileName).mkdirs();
System.out.println("Uncompressing archive at: " + destDir + "\\" + destFileName);
//Start reading through the archive and create the files in it
Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) zipEntries.nextElement();
if(zipEntry.isDirectory())
{
new File(destDir + "\\" + destFileName + "\\" + zipEntry.getName()).mkdirs();
continue;
}
InputStream input = zipFile.getInputStream(zipEntry);
FileOutputStream fo = new FileOutputStream(new File(destDir + "\\" + destFileName + "\\"
+ zipEntry.getName()));
while ((temp = input.read()) != -1)
{
fo.write(temp);
temp = 0;
}
fo.flush();
fo.close();
input.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment