我试了一次,没发现大小不一致啊,代码如下:import java.util.*;
import java.util.zip.*;
import java.io.*;class Test{ public static void main(String[] args) throws Exception {
byte[] buffer = "abcdefghigklmnopqrstuvwxyz0123456789".getBytes();
System.out.println("buffer's size:"+buffer.length);
 ByteArrayOutputStream o = new ByteArrayOutputStream();
//建立gzip压缩输出流
GZIPOutputStream gzout = new GZIPOutputStream(o);
gzout.write(buffer);
gzout.finish();
gzout.close();

//返回压缩字节流
byte[] data_ = o.toByteArray();
o.close();

//解压的代码:
byte[] buf = new byte[4096*2];
//建立字节数组输入流
ByteArrayInputStream i = new ByteArrayInputStream(data_);
//建立gzip解压输入流
GZIPInputStream gzin = new GZIPInputStream(i);
int size = gzin.read(buf);
i.close();
gzin.close();
byte b[] = new byte[size];
System.arraycopy(buf,0,b,0,size);
System.out.println("buf's size:"+size);
}}

解决方案 »

  1.   

    /**
     * 
     * 描述:压缩指定文件名的文件为zip格式
     * @param fileName
     */
    public static void jZip(String[] rgstring, String fileName) { ZipOutputStream zipoutputstream = null; try {
    zipoutputstream =
    new ZipOutputStream(new FileOutputStream(fileName)); zipoutputstream.setMethod(ZipOutputStream.DEFLATED); for (int i = 0; i < rgstring.length; i++) { File file = new File(rgstring[i]); byte[] rgb = new byte[1000]; int n = 0; FileInputStream fileinputstream = null; //Calculate the CRC-32 value.  This isn't strictly necessary
    //for deflated entries, but it doesn't hurt. CRC32 crc32 = new CRC32(); fileinputstream = new FileInputStream(file); while ((n = fileinputstream.read(rgb)) > -1) {
    crc32.update(rgb, 0, n);
    } fileinputstream.close(); //Create a zip entry. ZipEntry zipentry = new ZipEntry(file.getName()); logger.info(">>>>fileName<<<<" + file.getName()); zipentry.setSize(file.length());
    zipentry.setTime(file.lastModified());
    zipentry.setCrc(crc32.getValue()); //Add the zip entry and associated data. zipoutputstream.putNextEntry(zipentry); fileinputstream = new FileInputStream(file); while ((n = fileinputstream.read(rgb)) > -1) {
    zipoutputstream.write(rgb, 0, n);
    } fileinputstream.close(); } zipoutputstream.closeEntry(); zipoutputstream.close(); } catch (Exception e) {
    logger.info(e);
    }
    }
      

  2.   

    /**
         * 
         * 描述:解压缩zip文件
         * @param file
         */
    public static void jUnZip(String file) { try { ZipInputStream zipinputstream =
    new ZipInputStream(new FileInputStream(file)); while (true) {
    // Get the next zip entry.  Break out of the loop if there are
    //   no more. ZipEntry zipentry = zipinputstream.getNextEntry(); if (zipentry == null)
    break; // Read data from the zip entry.  The read() method will return
    //   -1 when there is no more data to read. byte[] rgb = new byte[1000]; int n; while ((n = zipinputstream.read(rgb)) > -1) {
    // In real life, you'd probably write the data to a file.
    } zipinputstream.closeEntry();
    } zipinputstream.close();
    } catch (Exception e) {
    logger.info(e);
    }
    }