While creating zip files from java the java.util.zip package is used for creating Zip files. The example below creates a Zip file from a normal text file. I think by looking at the code you can get idea about the logic behind the code. It is not that much complicated code. So, it don't need any type of explanation.
Code:
import java.io.*;
import java.util.zip.*;
class zipfile
{
public static void main(String[] args)
{
if (args.length != 2)
{
System.out.println("Usage: java zipfile[files to be zipped] [filename after zip] ");
return;
}
try
{
String fname = args[0];
String zipfname = args[1];
zipfilelist = new zipfile( );
list.doZip(fname,zipfname);
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void doZip(String fname,String zipfname)
{
try
{
byte[] buf = new byte[1024];
FileInputStream fileis = new FileInputStream(fname);
fileis.read(buf,0,buf.length);
CRC32 crc = new CRC32();
ZipOutputStream zoutstream = new ZipOutputStream((OutputStream)new FileOutputStream(zipfname));
zoutstream.setLevel(6);
ZipEntry entry = new ZipEntry(fname);
entry.setSize((long)buf.length);
crc.reset();
crc.update(buf);
entry.setCrc( crc.getValue());
zoutstream.putNextEntry(entry);
zoutstream.write(buf, 0, buf.length);
zoutstream.finish();
zoutstream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
Bookmarks