压缩并且保存到磁盘上
代码自己学习用~....import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;import sun.misc.BASE64Encoder;public class ZipUtil {public static final byte[] compress(String str, String fileName) {if (str == null)return null;byte[] compressed;ByteArrayOutputStream out = null;ZipOutputStream zout = null;try {out = new ByteArrayOutputStream();zout = new ZipOutputStream(out);zout.putNextEntry(new ZipEntry(fileName));zout.write(str.getBytes());zout.closeEntry();zout.finish();compressed = out.toByteArray();} catch (IOException e) {compressed = null;} finally {if (zout != null) {try {zout.close();} catch (IOException e) {}}if (out != null) {try {out.close();} catch (IOException e) {}}}return compressed;}/** * 将压缩后的 byte[] 数据解压缩 ** @param compressed * 压缩后的 byte[] 数据 * @return 解压后的字符串 */public static final String decompress(byte[] compressed) {if (compressed == null)return null;ByteArrayOutputStream out = null;ByteArrayInputStream in = null;ZipInputStream zin = null;String decompressed;try {out = new ByteArrayOutputStream();in = new ByteArrayInputStream(compressed);zin = new ZipInputStream(in);ZipEntry entry = zin.getNextEntry();byte[] buffer = new byte;int offset = -1;while ((offset = zin.read(buffer)) != -1) {out.write(buffer, 0, offset);}decompressed = out.toString();} catch (IOException e) {decompressed = null;} finally {if (zin != null) {try {zin.close();} catch (IOException e) {}}if (in != null) {try {in.close();} catch (IOException e) {}}if (out != null) {try {out.close();} catch (IOException e) {}}}return decompressed;}public static void testSaveZip(byte[] b, String fileName) throws IOException {String outFilename = "c:\\"+fileName+".zip";byte[] buf = new byte;FileOutputStream out = new FileOutputStream(outFilename);ByteArrayInputStream fos=new ByteArrayInputStream(b);int len = -1;while ((len = fos.read(buf))!=-1)out.write(buf, 0, len);out.close();}public static void main(String[] args) {String testStr = "测试,zip!";byte[] b = compress(testStr, "data");BASE64Encoder enc=new BASE64Encoder();System.out.println(enc.encode(b));String deCompress = decompress(b);System.out.println("--------------------------------------------");System.out.println(deCompress);try {testSaveZip(b,"data");} catch (IOException e) {e.printStackTrace();}}}
页:
[1]