我的想法是在构造函数中加载所有数据,然后重写read方法。我需要重写InputStream的所有方法吗?我尝试过在Google上搜索一些示例,但没有成功 - 你能给我一个链接吗?
available()
来知道要准备多少字节,我认为流使用默认实现也可以正常工作。 - Joachim Saueravailable()
只被定义为一个估计值。依赖于一个估计值的准确性是一个错误,在我看来。 - Joachim Sauer在实施我的InputStream
时,我遇到了一些非常重要的问题。
Override available(). As the Javadoc says:
The available method for class InputStream always returns 0. This method should be overridden by subclasses.
not overriding this method will causes that any tempt to test whether this stream is readable return false. For example, if you feed your inputStream
to a inputStreamReader
, this reader will always return false when you invoke reader.ready()
.
return -1 in the read()
. The doc didn't emphasize it:
If no byte is available because the end of the stream has been reached, the value -1 is returned. This method blocks until input data is available, the end of the stream is detected, or an exception is thrown.
if you choose to block read()
when no data is available, you have to remember to return -1
at some situations. Not doing this may causes that another read(byte b[], int off, int len)
blocks for the following code in the source:
for (; i < len ; i++) {// default len is a relative large number (8192 - readPosition)
c = read();
if (c == -1) {
break;
}
b[off + i] = (byte)c;
}
And this causes some(if not all) high level read block, like a reader's readLine(), read()
etc.
对于可能很大的数据,您可以使用来自guava的com.google.common.io.FileBackedOutputStream。
Javadoc: 一个OutputStream,它开始缓冲到字节数组,但一旦数据达到可配置大小,就切换到文件缓冲。
使用out.getSupplier().getInput()
,您可以获得InputStream。
完全没有必要创建自定义的InputStream
。只需使用ByteArrayInputStream
,就像这样:
public static InputStream createStream(){
final String csv = createCsvFromDataBaseValues();
return new ByteArrayInputStream(csv.getBytes());
}
特别是考虑到这个引用:
我的想法是在构造函数中加载所有的数据,然后重写读取方法。
如果你这样做,通过实现一个定制的 InputStream
,你不会得到任何好处。这与我上面概述的方法几乎相同。
Application
对象;每个对象在CSV文件中产生大约100个字符的一行。在内存中生成这样长的字符串是一个好主意还是最好创建一个临时文件,并在完成后传输它呢? - John ManakStringBuilder
和File
支持的版本来实现这个接口。 - Sean Patrick Floyd如果数据不太大,您可以:
String.getBytes(encoding)
)ByteArrayInputStream
中