构造指定大小的InputStream我第一个想到的就是使用SequenceInputStream进行拼接:方案一:
/**
* 获取指定大小的输入流
* @param streamLength 流大小
* @return InputSream
*/
public static InputStream getInputStreamByLength(long streamLength) {
int chunkSize = 500 * 1024 * 1024;
if (streamLength <= chunkSize) {
return new ByteArrayInputStream(new byte[(int) streamLength]);
} else {
int chunkCount = (int) Math.ceil(streamLength / (double) chunkSize);
ByteArrayInputStream chunkInputStream = new ByteArrayInputStream(new byte[chunkSize]);
if (chunkCount == 2) {
ByteArrayInputStream second_stream = new ByteArrayInputStream(new byte[(int) (streamLength - chunkSize)]);
return new SequenceInputStream(chunkInputStream, second_stream);
}
Vector<InputStream> vector = new Vector<InputStream>();
for (int i = 0; i < chunkCount-1; i++) {
vector.addElement(chunkInputStream);
}
vector.addElement(new ByteArrayInputStream(new byte[(int) (streamLength-(chunkCount-1)*chunkSize)]));
Enumeration<InputStream> e = vector.elements();
return new SequenceInputStream(e);
}
}
实际上只需要简单如下重写下read方法就行(太菜了我还是,还好),方案二:
long length = 1024;
int pos = 0;
public MyInputStream(long length) {
this.length = length;
}
public void setLength(long length){
this.length =length;
}
@Override
public int read() throws IOException {
return pos == length ? -1 : pos++;
}
}
网友评论