The most recent work requires the use of the GZIP format to compress text to reduce the size of the file, thus touching the Gzipinputstream/gzipoutputstream two classes, as well as the Bytearrayoutputstream class. Here is a simple example code to record, in case of a rainy moment.
Package com.ricky.java.test.junit;
Import Java.io.ByteArrayOutputStream;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStream;
Import Java.util.zip.GZIPInputStream;
Import Java.util.zip.GZIPOutputStream;
public class Gzipfiletest {private static final int buffer_size = 1024;
/** * @param args */public static void main (string[] args) {file Inputfile = new File ("D:/test/input.txt");
File outputfile = new file ("D:/test/test.dat");
Writegzip (Inputfile,outputfile);
Readgzip (outputfile);
The public static void Readgzip (file file) {Gzipinputstream gzipinputstream = null;
Bytearrayoutputstream BAOs = null;
try {gzipinputstream = new Gzipinputstream (new FileInputStream (file));
BAOs = new Bytearrayoutputstream ();
byte[] buf = new Byte[buffer_size];
int len = 0; while (Len=gzipinputstream.read (buf, 0, BuffeR_size)!=-1) {baos.write (buf, 0, Len);
} baos.tobytearray ();
String result = baos.tostring ("UTF-8");
System.out.println ("result=" +result);
catch (FileNotFoundException e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
}finally{if (gzipinputstream!=null) {try {gzipinputstream.close ();
catch (IOException e) {e.printstacktrace ();
} if (Baos!=null) {try {baos.close ();
catch (IOException e) {e.printstacktrace (); }}} public static void Writegzip (file inputfile, file outputfile) {Gzipoutputstream Gzipoutputstream =
Null
InputStream in = null;
try {gzipoutputstream = new Gzipoutputstream (new FileOutputStream (outputfile));
in = new FileInputStream (inputfile);
byte[] buffer = new Byte[buffer_size];
int len = 0;
while (len = In.read (buffer,0,buffer_size)) > 0) {gzipoutputstream.write (buffer, 0, Len); } gZipoutputstream.finish ();
catch (FileNotFoundException e) {e.printstacktrace ();
catch (IOException e) {e.printstacktrace ();
}finally{if (gzipoutputstream!=null) {try {gzipoutputstream.close ();
catch (IOException e) {e.printstacktrace ();
} if (In!=null) {try {in.close ();
catch (IOException e) {e.printstacktrace ();
}
}
}
}
}