Monday, January 16

COMPRESS A FILE INTO .gz FILE ~ COMPLETE JAVA CODE






Hello friends,

In this post I’m presenting a java code to compress a file into -.gz format.
Hope this will be useful to you..!!!

Algorithm
1.      1.Input the name of the file to be zipped.
2.      Create an OutputStream in the name of given _file.gz.
3.      Point it to the GZIPOutputStream.
4.       Read from the file to be zipped, bytewise, and write it into GZIPOutputStream.



import java.io.*;
import java.util.zip.*;
public class CompressFile {
public static void compresser(String temp) {
try {
File file = new File(temp);
FileOutputStream fout = new FileOutputStream(file + ".gz");
GZIPOutputStream gout = new GZIPOutputStream(fout);
FileInputStream fin = new FileInputStream(file);
BufferedInputStream in = new BufferedInputStream(fin);
byte[] buffer = new byte[1024];
int i;
while ((i = in.read(buffer)) >= 0) {
gout.write(buffer, 0, i);
}
System.out.println(" successfully compressed");
in.close();
gout.close();
}
catch (IOException e) {
System.out.println("Exception is" + e);
}
}
public static void main(String args[]) {
if (args.length != 1) {
System.out.println("Please enter the file name which needs to be compressed ");
} else {
compresser(args[0]);
}
}
}





For compiling::
javac CompressFile.java




For running::
java CompressFile any_file_name_present_in_current_directory


0 comments :

Post a Comment