Powered By Blogger

Friday, January 20, 2012

program to Unzip a file

/**
* This Unzip Unzips a zippedfile and returns the list of filesname unzipped
* @author Nitesh
*
*/
public class Unzip {

public static void main(String[] args) {
String dir = "E:\\data\\ad";
String zipFile = "zip.zip";
try{

Unzip list = new Unzip( );
List files = getUnZippedFile( dir, zipFile );
System.out.println("Unzipped file : ----------------");
for( File f : files ) {
System.out.println( f.getAbsolutePath() );
}
}
catch (Exception e)
{
e.printStackTrace();
}
}

/**
* Unzip all the files of the for 'zipfilename'. New folder created with the same name all the inner files
* written to the folder under the 'dir' directory
* @param dir
* @param zipFileName
* @return
*/
public static List getUnZippedFile(String dir, String zipFileName ) {

if ( dir == null || dir.length() == 0 || zipFileName == null || zipFileName.length() == 0 ) {
System.out.println("Cannot unzip. No Zip files found at location at directory : " + dir + " , filename :" + zipFileName );
return null;
}
if ( ! zipFileName.endsWith( ".zip") ) {
System.out.println("Unzipping fails. This file does not seem to be a ZipFile : " + zipFileName );
return null;
}
List unzipedFiles = null;
try {

File f = new File( dir, zipFileName );

byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(
new FileInputStream( f ));

zipentry = zipinputstream.getNextEntry();
unzipedFiles = new ArrayList();

while (zipentry != null) {
//for each entry to be extracted
/* if the zip folder is test.zip and has file atest.csv then entryName = test/atest.csv */
String entryName = zipentry.getName();
System.out.println("entryname "+entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File( entryName );
String innerZipFile = newFile.getName(); // e.g atest.csv

String parent = newFile.getParent(); // this determines if it is a folder zip or a file zip ??? strange , yep !
File ff = null;
if ( parent == null ) {
// This is the case of file zip. create a folder with the same name as 'zipfileName'
ff = new File( dir, zipFileName.substring(0, zipFileName.lastIndexOf("." ) ) );
}else {
ff = new File( dir, newFile.getParent() ); // create folder dir + test
}

if ( ! ff.exists() ) {
ff.mkdir() ;
}
File outputFile = new File( ff, innerZipFile );
fileoutputstream = new FileOutputStream( outputFile );

while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}

fileoutputstream.close();
zipinputstream.closeEntry();

unzipedFiles.add( outputFile );

zipentry = zipinputstream.getNextEntry();

}//while

zipinputstream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return unzipedFiles;
}
}

No comments:

Post a Comment