由于似乎没有真正的实现,我已经快速编写了一个初始实现来测试速度:
public class Buffer {
private int size;
private int writeIndex, writeOffset,
readIndex, readOffset;
private List<byte[]> backingArrays = new ArrayList<byte[]>();
public Buffer() {
this(10240);
}
public Buffer(int size) {
this.size = size;
}
public int read(byte [] bytes) {
return read(bytes, 0, bytes.length);
}
public int read(byte [] bytes, int offset, int length) {
int read = 0;
while(length > 0) {
byte [] input = getInput();
if (input == null) {
if (read == 0)
return -1;
else
return read;
}
int readLength = Math.min(length, (readIndex == writeIndex ? writeOffset : size) - readOffset);
System.arraycopy(input, readOffset, bytes, offset, readLength);
length -= readLength;
offset += readLength;
readOffset += readLength;
read += readLength;
}
return read;
}
public void write(byte [] bytes) {
write(bytes, 0, bytes.length);
}
public void write(byte [] bytes, int offset, int length) {
while (length > 0) {
byte [] output = getOutput();
int writeLength = Math.min(length, output.length - writeOffset);
System.arraycopy(bytes, offset, output, writeOffset, writeLength);
length -= writeLength;
offset += writeLength;
writeOffset += writeLength;
}
}
private byte[] getOutput() {
if (writeOffset >= size) {
writeIndex++;
writeOffset = 0;
}
if (backingArrays.size() <= writeIndex)
backingArrays.add(new byte[size]);
return backingArrays.get(writeIndex);
}
private byte [] getInput() {
if (backingArrays.size() == 0)
return null;
if (readOffset >= size) {
readIndex++;
readOffset = 0;
}
if (readIndex > writeIndex || (readIndex == writeIndex && readOffset >= writeOffset))
return null;
else
return backingArrays.get(readIndex);
}
public long size() {
return (long) size * (long) writeIndex + writeOffset;
}
}
我正在通过复制一个36兆字节的文件进行测试。当然,很多取决于文件交互,但总体而言,它似乎比bytearrayinputstream读取速度快40%,写入速度略快(增加了5-20%)
我很快就把它放在一起了,所以如果你发现任何错误,请告诉我。
编辑:
添加了一个功能,即默认情况下释放已读取的数组以供垃圾回收。