首先:
1、将文件转化为byte[]数组
private byte[] getBytesFromFile(File file) throws IOException {
InputStream in = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
throw new LogicException("文件过大,不能传输");
}
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead = in.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("不能转换,");
}
in.close();
return bytes;
}
a) 压缩:
public byte[] zip(byte[] data) {
byte[] b = null;
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(bos);
ZipEntry entry = new ZipEntry("~~~1.bmp");
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();
}
return b;
}
b) 解压缩:
public byte[] unZip(byte[] data) {
byte[] b = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
ZipInputStream zip = new ZipInputStream(bis);
while (zip.getNextEntry() != null) {
byte[] buf = new byte[1024];
int num = -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();
}
return b;
}