有没有一种方法可以使用 BufferedReader 读取 ByteBuffer,而不必先将其转换为 String?我想将相当大的 ByteBuffer 作为文本行读取,出于性能原因,我想避免将其写入磁盘。在 ByteBuffer 上调用 toString 不起作用,因为生成的 String 太大(它会抛出 java.lang.OutOfMemoryError:Java 堆空间)。我本以为 API 中会有一些东西可以将 ByteBuffer 包装在合适的阅读器中,但我似乎找不到合适的东西。
这是一个简短的代码示例,说明了我正在做的事情):
// input stream is from Process getInputStream()
public String read(InputStream istream)
{
ReadableByteChannel source = Channels.newChannel(istream);
ByteArrayOutputStream ostream = new ByteArrayOutputStream(bufferSize);
WritableByteChannel destination = Channels.newChannel(ostream);
ByteBuffer buffer = ByteBuffer.allocateDirect(writeBufferSize);
while (source.read(buffer) != -1)
{
buffer.flip();
while (buffer.hasRemaining())
{
destination.write(buffer);
}
buffer.clear();
}
// this data can be up to 150 MB.. won't fit in a String.
result = ostream.toString();
source.close();
destination.close();
return result;
}
// after the process is run, we call this method with the String
public void readLines(String text)
{
BufferedReader reader = new BufferedReader(new StringReader(text));
String line;
while ((line = reader.readLine()) != null)
{
// do stuff with line
}
}
目前尚不清楚为什么要使用字节缓冲区来开始。如果你有一个InputStream
如果你想读取它的行,为什么不直接使用InputStreamReader
包裹在一个BufferedReader
?蔚来汽车介入有什么好处?
Calling toString()
on a ByteArrayOutputStream
即使您有足够的空间,对我来说听起来也是一个坏主意:最好将其作为字节数组并将其包装在ByteArrayInputStream
然后一个InputStreamReader
,如果你真的必须有一个ByteArrayOutputStream
。如果你really想打电话toString()
,至少使用采用要使用的字符编码名称的重载 - 否则它将使用系统默认值,这可能不是您想要的。
编辑:好的,所以你真的想使用 NIO。您仍在写信给ByteArrayOutputStream
最终,您将得到一个包含数据的 BAOS。如果您想避免复制该数据,则需要从ByteArrayOutputStream
,例如这样:
public class ReadableByteArrayOutputStream extends ByteArrayOutputStream
{
/**
* Converts the data in the current stream into a ByteArrayInputStream.
* The resulting stream wraps the existing byte array directly;
* further writes to this output stream will result in unpredictable
* behavior.
*/
public InputStream toInputStream()
{
return new ByteArrayInputStream(array, 0, count);
}
}
然后您可以创建输入流,将其包装在InputStreamReader
,将其包裹在BufferedReader
,而你却离开了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)