是否有任何util类/方法采用大String并返回InputStream? [英] Any util class/method to take a large String and return an InputStream?
问题描述
我正在寻找一些使用util类/方法来占用较大的String
并返回InputStream
.
I am looking for some util class/method to take a large String
and return an InputStream
.
如果String
很小,我可以这样做:
If the String
is small, I can just do:
InputStream is = new ByteArrayInputStream(str.getBytes(<charset>));
但是,当String
很大(1MB,10MB或更大)时,当场分配一个比我的String大1到2倍(或更多?)的字节数组. (而且由于在完成所有编码之前您将不知道确切分配多少字节,所以我认为在分配最终字节数组之前必须分配其他数组/缓冲区.)
But when the String
is large(1MB, 10MB or more), a byte array 1 to 2 times(or more?) as large as my String is allocated on the spot. (And since you won't know how many bytes to allocate exactly before all the encoding is done, I think there must be other arrays/buffers allocated before the final byte array is allocated).
我对性能有要求,并且想优化此操作.
I have performance requirements, and want to optimize this operation.
理想情况下,我认为,正在寻找的类/方法会在消耗InputStream的同时一次对一个小块的字符进行动态编码,因此内存分配不会激增.
Ideally I think, the class/method I am looking for would encode the characters on the fly one small block at a time as the InputStream is being consumed, thus no big surge of mem allocation.
查看apache commons IOUtils.toInputStream(..)
的源代码,我发现它还可以一次性将String转换为大字节数组.
Looking at the source code of apache commons IOUtils.toInputStream(..)
, I see that it also converts the String to a big byte array in one go.
并且StringBufferInputStream
已过时,并且不能正确执行该工作.
And StringBufferInputStream
is Deprecated, and does not do the job properly.
任何地方都有这样的util类/方法吗?还是我可以写几行代码来做到这一点?
Is there such util class/method from anywhere? Or I can just write a couple of lines of code to do this?
对此的功能需求是,在其他地方,我正在使用util方法,该方法采用InputStream
并从该InputStream
中流出字节.
The functional need for this is that, elsewhere, I am using a util method that takes an InputStream
and stream out the bytes from this InputStream
.
我似乎还没有其他人在寻找这样的东西.我在某处误东西了吗?
I haven't seem other people looking for something like this. Am I mistaking something somewhere?
我已经开始为此编写自定义类,但是如果有更好/合适/正确的解决方案/更正我的需求,它将停止.
I have started writing a custom class for this, but would stop if there is a better/proper/right solution/correction to my need.
推荐答案
Java内置库假定您只需要在输出而不是输入中将char转换为字节即可. Apache Commons IO库具有
The Java built-in libraries assume you'd only need to go from chars to bytes in output, not input. The Apache Commons IO libraries have ReaderInputStream, however, which can wrap a StringReader
to get what you want.
这篇关于是否有任何util类/方法采用大String并返回InputStream?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!