java中 檔案壓縮處理

weixin_30788239發表於2020-04-05
public static void main(String[] args) throws IOException {
        File file=new File("./mhxx_configs.xml");
        File zip=new File("./mhxx.zip");
        String name="configs.txt";                                    //壓縮包裡檔案的名字
        InputStream iStream=new FileInputStream(file);
        FileOutputStream oStream=new FileOutputStream(zip);
        ZipOutputStream zStream=new ZipOutputStream(oStream);
        byte[] a=new byte[iStream.available()];
        zStream.putNextEntry(new ZipEntry(name));                         //一定要有  name為壓縮包裡檔名
        int read=0;
        while((read=iStream.read(a))>0) {
            zStream.write(a, 0, read);                                   //簡單的檔案壓縮
        }
        
        ByteArrayOutputStream bStream=new ByteArrayOutputStream();       
        ZipOutputStream zStream2=new ZipOutputStream(bStream);
        zStream2.putNextEntry(new ZipEntry(name));
        zStream2.write(a);
        a=bStream.toByteArray();                                         //把檔案壓縮為byte[]    
        for(byte b:a) {
            System.out.print(b+" ");
        }
        
        
        zStream.closeEntry();                                           //流一定要記得關 不關  結果各種操蛋
        zStream.close();
        zStream2.close();
        iStream.close();
        oStream.close();
        bStream.close();

 

轉載於:https://www.cnblogs.com/qiangqiangqiang/p/7743838.html

相關文章