当前位置: 代码迷 >> J2SE >> 压缩byte数组解决思路
  详细解决方案

压缩byte数组解决思路

热度:147   发布时间:2016-04-24 02:16:44.0
压缩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
  相关解决方案