1.compress(String):對字串進行ZIP壓縮餅返回位元組數組
2.decompress(byte[]):將壓縮的位元組數組還原成字串
用途:可用於將字串儲存到資料庫BOLB中。
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; public class StringCompress { public static final byte[] compress(String paramString) { if (paramString == null) return null; ByteArrayOutputStream byteArrayOutputStream = null; ZipOutputStream zipOutputStream = null; byte[] arrayOfByte; try { byteArrayOutputStream = new ByteArrayOutputStream(); zipOutputStream = new ZipOutputStream(byteArrayOutputStream); zipOutputStream.putNextEntry(new ZipEntry("0")); zipOutputStream.write(paramString.getBytes()); zipOutputStream.closeEntry(); arrayOfByte = byteArrayOutputStream.toByteArray(); } catch (IOException localIOException5) { arrayOfByte = null; } finally { if (zipOutputStream != null) try { zipOutputStream.close(); } catch (IOException localIOException6) { } if (byteArrayOutputStream != null) try { byteArrayOutputStream.close(); } catch (IOException localIOException7) { } } return arrayOfByte; } @SuppressWarnings("unused") public static final String decompress(byte[] paramArrayOfByte) { if (paramArrayOfByte == null) return null; ByteArrayOutputStream byteArrayOutputStream = null; ByteArrayInputStream byteArrayInputStream = null; ZipInputStream zipInputStream = null; String str; try { byteArrayOutputStream = new ByteArrayOutputStream(); byteArrayInputStream = new ByteArrayInputStream(paramArrayOfByte); zipInputStream = new ZipInputStream(byteArrayInputStream); ZipEntry localZipEntry = zipInputStream.getNextEntry(); byte[] arrayOfByte = new byte[1024]; int i = -1; while ((i = zipInputStream.read(arrayOfByte)) != -1) byteArrayOutputStream.write(arrayOfByte, 0, i); str = byteArrayOutputStream.toString(); } catch (IOException localIOException7) { str = null; } finally { if (zipInputStream != null) try { zipInputStream.close(); } catch (IOException localIOException8) { } if (byteArrayInputStream != null) try { byteArrayInputStream.close(); } catch (IOException localIOException9) { } if (byteArrayOutputStream != null) try { byteArrayOutputStream.close(); } catch (IOException localIOException10) { } } return str; } }
轉自【http://www.open-open.com/lib/view/open1374372029683.html】