其他分享
首页 > 其他分享> > 用ByteArrayOutPutStream和ZipOutputStream实现压缩形成二进制,方便网络传输

用ByteArrayOutPutStream和ZipOutputStream实现压缩形成二进制,方便网络传输

作者:互联网

代码如下:
public class Test1 {
public static void main(String[] args) {
try {
zip();
} catch (IOException e) {
e.printStackTrace();
}
}

public static void zip() throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ZipOutputStream zos = new ZipOutputStream(baos);
    zos.putNextEntry(new ZipEntry("a/"));
    zos.closeEntry();
    zos.putNextEntry(new ZipEntry("a/1.txt"));
    zos.closeEntry();
    zos.close();

	//读取二进制,将其还原为文件
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    byte[] b = new byte[1024];
    int len;
    FileOutputStream fos = new FileOutputStream(new File("d:/ce/1.zip"));
    while ((len = bais.read(b)) != -1) {
        fos.write(b,0,len);
    }
    fos.close();
    bais.close();
    baos.close();
}

}

标签:ZipOutputStream,bais,zip,二进制,ByteArrayOutPutStream,baos,zos,new,close
来源: https://blog.csdn.net/jiamaa/article/details/122456427