本文介绍了在Java中将字节流转换为字符流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我认为有一个类,我们可以通过指定编码,feed字节流来创建它,并从中获得字符流?主要的是我想通过不同时在内存中同时拥有全部字节流数据和整个字符流数据来节省内存。
I think there is that one class where we can create it by specifying the encoding, feed byte streams into it and get character streams from it? The main point is I want to conserve memory by not having both entire byte-stream data and entire character-stream data in the memory at the same time.
类似的东西:
Something s = new Something("utf-8");
s.write(buffer, 0, buffer.length); // it converts the bytes directly to characters internally, so we don't store both
// ... several more s.write() calls
s.close(); // or not needed
String text = s.getString();
// or
char[] text = s.getCharArray();
这是什么东西?
推荐答案
你可以使用 CharsetDecoder
来模拟它。
You can probably mock it up using CharsetDecoder
. Something along the lines of
CharsetDecoder decoder = Charset.forName(encoding).newDecoder();
CharBuffer cb = CharBuffer.allocate(100);
decoder.decode(ByteBuffer.wrap(buffer1), cb, false);
decoder.decode(ByteBuffer.wrap(buffer2), cb, false);
...
decoder.decode(ByteBuffer.wrap(bufferN), cb, true);
cb.position(0);
return cb.toString();
(是的,我知道这会溢出你的 CharBuffer
- 您可能想要将内容复制到 StringBuilder
中。)
(Yes, I know this will overflow your CharBuffer
-- you may want to copy the contents into a StringBuilder
as you go.)
这篇关于在Java中将字节流转换为字符流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!