ByteArrayOutputStream 的toByteArray(),文件一大就报内存溢出
package com.yh.android.util;import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;public class DataCompression {

/**
 * 将压缩后的 byte[] 数据解压缩
 * 
 * @param compressed
 *            压缩后的 byte[] 数据
 * @return 解压后的字符串
 * @throws ClassNotFoundException 
 */
//服务器端解压,将一个byte[]解压出多个byte[],就是每张图片
public static final ArrayList<byte[]> decompress(byte[] compressed) {
if (compressed == null)
return null; ByteArrayOutputStream out = null;
ByteArrayInputStream in = null;
ZipInputStream zin = null;
Object decompressed;
ArrayList<byte[]> retList = new ArrayList<byte[]>();
try {
in = new ByteArrayInputStream(compressed);
zin = new ZipInputStream(in);
while (zin.getNextEntry() != null) {
out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int offset = -1;
while ((offset = zin.read(buffer)) != -1) {
out.write(buffer, 0, offset);
}
ByteArrayInputStream in1 = new ByteArrayInputStream(out.toByteArray());
ObjectInputStream ois = new ObjectInputStream(in1);
decompressed = ois.readObject();
retList.add((byte[])decompressed);
}
return retList;
} catch (Exception e) {
e.printStackTrace();
retList = 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 retList;
}

/**
 * 压缩字符串为 byte[] 储存可以使用new sun.misc.BASE64Encoder().encodeBuffer(byte[] b)方法
 * 保存为字符串
 * 
 * @param str
 *            压缩前的文本
 * @return
 */
//将多张图片的byte[]压缩成一个byte[]往服务器发送
public static final byte[] compress(ArrayList<byte[]> byteList) {
if (byteList == null)
return null; byte[] compressed = null;
ByteArrayOutputStream out = null;
ZipOutputStream zout = null; try {
out = new ByteArrayOutputStream();
zout = new ZipOutputStream(out);
for (int i=0;i<byteList.size();i++) {
zout.putNextEntry(new ZipEntry("" + i));
ByteArrayOutputStream out1 = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out1);
oos.writeObject(byteList.get(i));

byte[] bytes = out1.toByteArray();//图片一大于2M就报内存溢出

//不使用ByteArrayOutputStream的话,zout报内存溢出
zout.write(bytes);
zout.closeEntry();


}
compressed = out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
compressed = null;
} finally {
if (zout != null) {
try {
zout.close();
} catch (IOException e) {
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
}
}
}
return compressed;
}
}在线等