To begin with Zip step by step, let us look at the directory and file location and structure to appreciate the codes we are going to write.

The following routines will accomplish the followings.

  • create a directory if does not exits, if you delete this myfirst directory and try that

I removed the directory and run the routine

\

Note the myfile is created

Zip file is created

 

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.zip.ZipFile;// needed ZipFile
import java.util.Enumeration;//needed enumeration

//javac Test_ZipEntry.java
//java -classpath . Test_ZipEntry
public class Test_ZipEntry {

public static void main(String[] args) throws Exception
{

//System.out.println(new File("c:/myjava/File_Class/myfirst").mkdir());
String str = "c:/myjava/File_Class/myfirst";
String fpath = "c:/myjava/File_Class/mynew.txt";
String fileunpack = "c:/myjava/File_Class/myfirst/mynew.txt";
String strzip = "c:/myjava/File_Class/myfirst/myfirst.zip";
boolean b1;
File dir = new File(str);
// if directory exits delete if does not then create
if(! dir.isDirectory())
{
new File("c:/myjava/File_Class/myfirst").mkdir();
System.out.println("directory "+ dir.getName()+" Created");}
else {System.out.println("directory exists");}
byte[] data =new byte[2048]; int bytecount=0;
ZipOutputStream out = new ZipOutputStream(new FileOutputStream("c:/myjava/File_Class/myfirst/myfirst.zip"));
BufferedInputStream in = new BufferedInputStream(new FileInputStream(fpath));

try {
ZipEntry entry = new ZipEntry(fileunpack);
System.out.println("Compressing " + fpath);
out.putNextEntry(entry);
while((bytecount = in.read(data, 0,2048))!=-1)
{
out.write(data,0,bytecount);
}

} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
System.out.println("Compressing " + bytecount);
in.close();
out.close();
}

Can_Unzip cu = new Can_Unzip();
cu.method_1(strzip);
}
}
class Can_Unzip
{
public void method_1(String str)throws Exception
{
ZipFile zf = new ZipFile(str);
Enumeration e = zf.entries();
int len=0; byte[] buffer = new byte[2048];
while (e.hasMoreElements()) {
ZipEntry entry = (ZipEntry)e.nextElement();
if(entry.isDirectory()){ System.out.println("Extracting" + entry.getName());
(new File(entry.getName())).mkdir(); continue;
}
InputStream in = zf.getInputStream(entry);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(entry.getName()));
while((len = in.read(buffer))>=0)
{
out.write(buffer, 0, len);
}
in.close();
out.close();
}
zf.close();
}
}