java file compression ZipOutPutStream

In fact, the best book is javaAPI

1. Create ZipOutPutStream stream, using a speed BufferedOutputStream mention.

2. Create a new zip method for compressing files, parameter passing

Methods putNextEntry 3.zip where writing to the directory

4. recursive directory array

5. Write data stream off

 

/ ** 
 * Compression 
 * @author BinPeng 
 * @date 2019/8/6 18:19 
 * / 
public class Zip18 { 
    public static void main (String [] args) throws IOException { 
        COMPRESSIon ( "F.: \\ test.zip" , new File ( "F: \\ test")); // the first parameter is the name of compression, the second parameter is compressed to the directory 
    } 
    Private static void cOMPRESSIon (String zipFileName, File target) throws IOException {/ / compression 
        System.out.println ( "compressed file ..."); 
        the ZipOutputStream the ZipOutputStream new new OUT = (new new a FileOutputStream (zipFileName)); 
        BufferedOutputStream The new new BufferedOutputStream The BOS = (OUT); 
        ZIP (OUT, target, target.getName () , BOS); 
        bos.close (); 
        out.close (); 
        System.out.println ( "Compression Complete "); 
    }
 
    Private static void ZIP (the ZipOutputStream Zout, File target, String name, BufferedOutputStream The BOS) throws IOException { 
        // judgment is not a directory 
        IF (target.isDirectory ()) { 
          File [] = target.listFiles Files (); 
          IF (Files .length == 0) {// empty directory 
              zout.putNextEntry (the ZipEntry new new (name + "/")); 
            / * start writing a new ZIP file entry and positions the stream to the beginning of the entry data. 
              Closes the current entry, if still valid. If no compression method for the entry, 
              the default compression method, if the entry is not set modification time, the current time. * / 
          } 
          For (File F: Files) { 
              // recursive process 
              ZIP (Zout, F, name + "/" + f.getName (), BOS); 
          } 
        } the else { 
                zout.putNextEntry (the ZipEntry new new (name));
                InputStream inputStream=new FileInputStream(target);
                BufferedInputStream bis=new BufferedInputStream(inputStream);
                byte[] bytes=new byte[1024];
                int len=-1;
                while ((len=bis.read(bytes))!=-1){
                    bos.write(bytes,0,len);
                }
                bis.close();

        }

    }

}

  

Guess you like

Origin www.cnblogs.com/july7/p/11316721.html