Code for Java compression
import java.io.*;
import java.util.zip.*;
/** Compresses a file into a GZip archive. **/
public class SimpleGZip
{
public static void main(String[] args)
{
if(args.length<1)
{
System.out.println("Usage: Java SimpleGZip fileName");
System.exit(0);
}
String fileName = args[0];
try{makeGZip(fileName);}
//try{makeZip(fileName);}
catch(Exception e){System.err.println(e);}
}
/** Creates a GZip archive using the file name passed in as a **/
public static void makeGZip(String fileName) throws IOException, FileNotFoundException
{
File file = new File(fileName);
FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin);
//if input file is a.txt, then output file is a.txt.gz
FileOutputStream fos = new FileOutputStream(file + ".gz");
GZIPOutputStream gzos = new GZIPOutputStream(fos);
byte[] buf = new byte[1024];
int len;
//Store the length of a line
while((len = in.read(buf)) >= 0)
{
gzos.write(buf, 0, len);
}
in,close();
gzos.close();
}
/** Creates a Zip archive. If the filename passed in is a directory, the directory's contents will be made into a Zip file **/
public static fvoid makeZip(String fileName) throws IOException, FileNotFoundException
{
File file = File(fileName);
zos = new ZipOutputStream(new FileOutputStream(file + ".zip"));
recurseFiles(file);
zos.close();
}
/** Recurses down a directory and its subdirectories to look for files to add to the Zip. If the current file being looked at is not a directory, the method adds it to the Zip file. **/
private static void recurseFiles(File file) throws IOException, FileNotFoundException
{
if(file.isDirectory())
{
String[] fileNames = file.list();
if(fileNames != null)
for(int i=0; i<fileNames.length; i++)
recurseFiles(new File(file, fileNames[i]));
//file, fileNames[i] for full path
}else
{
FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = BufferedInputStream(fin);
byte[] buf = new byte[1024];
int len;
ZipEntry zipEntry = new ZipEntry(file.toString());
zos.putNextEntry(zipEntry);
while((len = in.read(buf)) >= 0)
{
gzos.write(buf, 0, len);
}
in,close();
gzos.closeEntry();
}
}