Java 实现压缩文件

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());
        }
    }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值