Gzip Single File compression
Use gzip compression for individual files.
Package Date0805.demo1;import Java.io.bufferedinputstream;import Java.io.bufferedoutputstream;import java.io.File; Import Java.io.fileinputstream;import Java.io.fileoutputstream;import Java.io.inputstream;import Java.io.outputstream;import Java.util.zip.gzipoutputstream;public class Gziprunnable implements Runnable {private Final file file;public gziprunnable (file file) {This.file=file;} @Overridepublic void Run () {if (!file.getname (). EndsWith (". gz")) {file Outputfile=new file (File.getparent (), File.getname () + ". Gz"); if (!outputfile.exists ()) {Counttime counttime = new Counttime (file); Thread t=new thread (counttime); T.start (); try (InputStream in =new bufferedinputstream (new FileInputStream (file)); O Utputstream out=new Bufferedoutputstream (New Gzipoutputstream (New FileOutputStream (OutputFile)));) {int B;while ((B=in.read ())!=-1) Out.write (b); Out.flush ();} catch (Exception ex) {ex.printstacktrace ();} T.interrupt ();} else {System.out.println (outputfile+ "file already exists, cannot be compressed!");}}}
Creating a thread pool for recursive compression
to implement compression for all sub-files under a folder, first recursively find all the child files and then call the compression thread to compress.
Package Date0805.demo1;import Java.io.file;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;public class Gzipfiles {private final static int thread_count=4;private static Executorservice Service=executors.newfixedthreadpool (thread_count);p ublic static void GZip (File Fileargs) {if (! Fileargs.isdirectory ()) {gziprunnable gziprunnable = new gziprunnable (Fileargs); Service.submit (GZipRunnable);} else {file[] files = fileargs.listfiles (); for (File f:files) {GZip (f);}}} public static void Shutdown () {Service.shutdown ();}}
Compression tips
Package Date0805.demo1;import Java.io.file;public class Counttime implements Runnable {private File File;public Counttime (file file) {super (); this.file = file;} @Overridepublic void Run () {System.out.println ("compressing" +file.getabsolutepath ()); try {while (true) {System.out.print ("."); Thread.Sleep (1000);}} catch (Interruptedexception e) {System.out.println (); System.out.println (File.getabsolutepath () + ". GZ has been compressed done!" ");}}}
Test code
Package Date0805.demo1;import Java.io.file;public class Test {public static void main (string[] args) {file File=new file (" d:\\ new Folder "); Gzipfiles.gzip (file); Gzipfiles.shutdown ();}}
Recursively compress all sub-files under a folder using the thread pool