有沒有辦法用BufferedReader讀取ByteBuffer,而不必首先將它變成String?我想通讀一個相當大的ByteBuffer作爲文本行,並且出於性能原因,我想避免將它寫入磁盤。在ByteBuffer上調用toString不起作用,因爲結果字符串太大(它會拋出java.lang.OutOfMemoryError:Java堆空間)。我原以爲API中會有東西將一個ByteBuffer包裝在合適的閱讀器中,但我似乎無法找到任何合適的東西。用於大型ByteBuffer的BufferedReader?
下面是一個簡短的代碼示例說明了我在做什麼):
// 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)做任何處理,直到流程完成,所以我需要將它放入緩衝區中以供稍後閱讀。 – Rob 2009-06-25 19:19:03
因此把它放入ByteArrayOutputStream的字節數組中。一旦你把它作爲一個字節數組,你就沒事。無論如何,這正是NIO所要做的,而BAOS則更簡單。如果它會很大,你可能會想要派生你自己的ByteArrayOutputStream,它可以讓你直接訪問字節數組,所以你不用擔心用toByteArray()創建一個副本。這是一個恥辱ByteArrayOutputStream沒有「toByteArrayInputStream」,讓你直接從它讀取... – 2009-06-25 19:24:57