Java 實現壓縮檔

來源:互聯網
上載者:User

Java comes with “java.util.zip” library to implement the data compression in ZIp format. The overall concept is quite straightforward.

·Read file with “FileInputStream
·Add the file name to “ZipEntry” and output it to “ZipOutputStream

Simple ZIP example

Read a file “C:\\user.txt” and compress it into a zip file – “C:\\user.zip“.

    package org.hello.zip;    import java.io.FileInputStream;    import java.io.FileOutputStream;    import java.io.IOException;    import java.util.zip.ZipEntry;    import java.util.zip.ZipOutputStream;    public class JavaZip {        public static void main(String[] args) {            byte[] buffer = new byte[1024];            try {                FileOutputStream fos = new FileOutputStream("C:\\user.zip");                ZipOutputStream zos = new ZipOutputStream(fos);                ZipEntry ze = new ZipEntry("user.txt");                zos.putNextEntry(ze);                FileInputStream in = new FileInputStream("C:\\user.txt");                /*                 * int java.io.FileInputStream.read(byte[] b) throws IOException                 * Reads up to b.length bytes of data from this input stream into an                 * array of bytes. This method blocks until some input is available.                 * Overrides: read(...) in InputStream Parameters: b the buffer into                 * which the data is read. Returns: the total number of bytes read                 * into the buffer, or -1 if there is no more data because the end                 * of the file has been reached.                 */                int len;                while ((len = in.read(buffer)) > 0) {                    zos.write(buffer, 0, len);                }                in.close();                zos.closeEntry();                zos.close();                System.out.println("Compress Completed!");            } catch (IOException e) {                e.printStackTrace();            }        }    }

Advance ZIP example – Recursively

Read all files from folder “C:\\Logs” and compress it into a zip file – “C:\\Logs.zip“. It will recursively zip a directory as well.

    package org.hello.zip;    import java.io.File;    import java.io.FileInputStream;    import java.io.FileOutputStream;    import java.io.IOException;    import java.util.ArrayList;    import java.util.List;    import java.util.zip.ZipEntry;    import java.util.zip.ZipOutputStream;    public class AppZip {        List<String> fileList;        private static final String OUTPUT_ZIP_FILE = "C:\\Logs.zip";        private static final String SOURCE_FOLDER = "C:\\Logs";                AppZip(){            fileList =new ArrayList<String>();        }                public static void main(String[] args){            AppZip appzip = new AppZip();            appzip.generateFileList(new File(SOURCE_FOLDER));            appzip.zipIt(OUTPUT_ZIP_FILE);        }        private void zipIt(String zipFile) {            byte[] buffer = new byte[1024];            try{                FileOutputStream fos = new FileOutputStream(zipFile);                ZipOutputStream zos = new ZipOutputStream(fos);                System.out.println("Output to Zip: "+ zipFile);                for(String filename :this.fileList){                    System.out.println("File added: "+filename);                    ZipEntry ze = new ZipEntry(filename);                    zos.putNextEntry(ze);                                        FileInputStream in = new FileInputStream(SOURCE_FOLDER + File.separator + filename);                                        int len;                    while((len = in.read(buffer)) > 0){                        zos.write(buffer,0,len);                    }                    in.close();                }                zos.closeEntry();                zos.close();                System.out.println("Compress Completed.");                            }catch(IOException e){                e.printStackTrace();            }                    }        /**         * Traverse a directory and get all files,         * and add the file into fileList         * @param node file or directory         */        private void generateFileList(File node) {            //add file only            if(node.isFile()){                fileList.add(generateZipEntry(node.getAbsoluteFile().toString()));            }                    if(node.isDirectory()){                String[] subNote = node.list();                for(String filename : subNote){                    generateFileList(new File(node, filename));                }            }                }         /**         * Format the file path for zip         * @param file file path         * @return Formatted file path         */        private String generateZipEntry(String filename) {            return filename.substring(SOURCE_FOLDER.length()+1, filename.length());        }    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.