How to make a gzip file in Java?
To create a GZIP file, you can use GZIPOutputStream class provided by java.util.zip package.Here is an example,
String outFilename = "GZIPTest.txt.gz";
String inFilename = "Test.txt";
BufferedWriter bufferedWriter = null;
BufferedReader bufferedReader = null;
try {
//Construct the BufferedWriter object
bufferedWriter = new BufferedWriter(
new OutputStreamWriter(
new GZIPOutputStream(new FileOutputStream(outFilename))
));
//Construct the BufferedReader object
bufferedReader = new BufferedReader(new FileReader(inFilename));
String line = null;
// from the input file to the GZIP output file
while ((line = bufferedReader.readLine()) != null) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
//Close the BufferedWrter
if (bufferedWriter != null) {
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//Close the BufferedReader
if (bufferedReader != null ){
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
How to uncompress a file in the gzip format?
This example decompresses a gzip compressed file with java.util.zip.GZIPInputStream.public static boolean Uncompression(String infname, String outfname){
GZIPInputStream in = null;
OutputStream out = null;
try {
in = new GZIPInputStream(new FileInputStream(infname));
out = new FileOutputStream(outfname);
byte[] buf = new byte[65536];
int len;
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
in.close();
out.close();
return true;
} catch (IOException e) {
if ( in != null ) {
try {
in.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if ( out != null ) {
try {
out.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
return false;
}
}
0 comments:
Post a Comment