63 行代码加速了我的应用程序:
import java.io.IOException;
import java.io.OutputStream;
public class CustomByteArrayOutputStream extends OutputStream {
protected byte[] buf;
protected int count;
public CustomByteArrayOutputStream() {
buf = new byte[32];
}
public CustomByteArrayOutputStream(int size) {
if (size >= 0)
buf = new byte[size];
else
throw new IllegalArgumentException("size < 0");
}
@Override
public void close() throws IOException {
super.close();
}
public byte[] getData() {
return buf;
}
private void expand(int i) {
if (count + i <= buf.length)
return;
byte[] newbuf = new byte[(count + i) * 2];
if (buf.length > 0)
System.arraycopy(buf, 0, newbuf, 0, count);
buf = newbuf;
}
public synchronized void reset() {
count = 0;
}
public int size() {
return count;
}
@Override
public synchronized void write(int oneByte) {
if (count == buf.length)
expand(1);
buf[count++] = (byte) oneByte;
}
@Override
public synchronized void write(byte[] buffer, int offset, int len) {
if (len == 0)
return;
expand(len);
System.arraycopy(buffer, offset, buf, count, len);
count += len;
}
}
如果不知道确切的大小,请执行以下操作: new CustomByteArrayOutputStream(0); 这不会创建任何东西,并且在第一次写入时大小会自动增加。
getData() - 在不复制的情况下获取数据,但不要忘记在获取数据时应该始终获取数据的大小。