檔案ZIp的對byte[]的壓縮和解壓縮
首先:
1、將檔案轉化為byte[]陣列
privatebyte[] getBytesFromFile(File file) throws IOException {
InputStream in = new FileInputStream(file);
longlength = file.length();
if (length > Integer.MAX_VALUE) {
thrownew LogicException("檔案過大,不能傳輸");
}
byte[] bytes
intoffset = 0;
intnumRead = 0;
while (offset < bytes.length && (numRead = in.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
thrownew IOException(
}
in.close();
returnbytes;
}
a) 壓縮:
publicbyte[] zip(byte[] data) {
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(bos);
ZipEntry entry
entry.setSize(data.length);//返回條目資料的未壓縮大小;如果未知,則返回 -1。
zip.putNextEntry(entry);// 開始寫入新的 ZIP 檔案條目並將流定位到條目資料的開始處
zip.write(data);//將位元組陣列寫入當前 ZIP 條目資料。
zip.closeEntry();
zip.close();
b = bos.toByteArray();
} catch (Exception ex) {
ex.printStackTrace();
}
returnb;
}
b) 解壓縮:
publicbyte[] unZip(byte[] data) {
byte[] b = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ZipInputStream zip = new ZipInputStream(bis);
while (zip.getNextEntry() != null) {
byte[] buf = newbyte[1024];
intnum = -1;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((num = zip.read(buf, 0, buf.length)) != -1) {
baos.write(buf, 0, num);
}
b = baos.toByteArray();
baos.flush();
baos.close();
}
zip.close();
bis.close();
} catch (Exception ex) {
ex.printStackTrace();
}
returnb;
}