日期:2014-05-20  浏览次数:20921 次

压缩byte数组
将byte数组压缩后直接生成byte数组,途中不生成文件怎么解决?


------解决方案--------------------
Java code

public static void main(String[] args) throws IOException {
        String content = "国考其实真的还不如科举考试,真正状元什么的都是要殿试的,皇帝亲自考试。另外作弊全是欺君之";
        ByteArrayOutputStream result = new ByteArrayOutputStream();
        ZipOutputStream outputStream = new ZipOutputStream(result);
        ZipEntry entry=new ZipEntry("tttt.txt");
        entry.setSize(content.getBytes().length);
        entry.setTime(new Date().getTime());
        
        outputStream.putNextEntry(entry);
        outputStream.write(content.getBytes());
        outputStream.flush();
        outputStream.close();
        
        //result.toByteArray();#压缩后的字节
        
        FileOutputStream file=new FileOutputStream("e:/test111.zip");
        file.write(result.toByteArray());
        file.flush();
        file.close();
    }

------解决方案--------------------
Java code

byte[] data = "将byte数组压缩后直接生成byte数组,途中不生成文件怎么解决?".getBytes();
        
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gos = new GZIPOutputStream(baos);
        gos.write(data);
        gos.close();
        byte[] dataAfterExp = baos.toByteArray();
        System.out.println(Arrays.toString(data));
        System.out.println(Arrays.toString(dataAfterExp));
        //TODO close
        
        //弄回来
        byte[] tmp = new byte[10240];
        GZIPInputStream gis = new GZIPInputStream(new ByteArrayInputStream(dataAfterExp));
        int length = 0;
        int pos = 0;
        while((length = gis.read(tmp, pos, 64)) > 0) {
            pos += length;
        }
        
        System.out.println(Arrays.toString(tmp));
        //TODO close