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

关于流
怎么把一个一个String做成zip放到流里面。

------解决方案--------------------
Java自带组件包可以帮助实现的:java.util.zip.* 

Google下样例代码吧。
------解决方案--------------------
String短的话,压缩反而浪费容量。不如拼装成一个超长的String。

Java code

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipTest {
    public static void main(String[] args) {

        /* 得到String被Zip后的二进制数组 */
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ZipOutputStream zos = new ZipOutputStream(baos);
        try {
            zos.putNextEntry(new ZipEntry("1"));
            zos.write("Hello你好Hello".getBytes());
            zos.putNextEntry(new ZipEntry("2"));
            zos.write("World世界World".getBytes());
            zos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        byte[] zipedData = baos.toByteArray();
        System.out.println(zipedData.length + ": " + Arrays.toString(zipedData));

        /* 将被Zip的数据还原为String */
        ByteArrayInputStream bais = new ByteArrayInputStream(zipedData);
        ZipInputStream zis = new ZipInputStream(bais);
        try {
            byte[] tmp = new byte[4096];
            while (zis.getNextEntry() != null) {
                int size = zis.read(tmp);
                String msg = new String(tmp, 0, size);
                System.out.println("Got: " + msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

------解决方案--------------------
google 有现成的代码啊