3

有没有办法用 BufferedReader 读取 ByteBuffer 而不必先将其转换为 String ?我想将相当大的 ByteBuffer 作为文本行读取,出于性能原因,我想避免将其写入磁盘。在 ByteBuffer 上调用 toString 不起作用,因为生成的 String 太大(它抛出 java.lang.OutOfMemoryError: Java heap space)。我原以为 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
  }
}
4

3 回答 3

5

目前尚不清楚为什么要使用字节缓冲区开始。如果你有一个InputStream并且你想读它的行,你为什么不直接使用一个InputStreamReader包裹在 a 中的BufferedReader?让蔚来参与有什么好处?

即使你有足够的空间,调用toString()aByteArrayOutputStream对我来说也是个坏主意:如果你真的需要 a ,最好将它作为一个字节数组并将其包装在 a 中ByteArrayInputStream,然后是 an 。如果你真的想调用,至少使用使用字符编码名称的重载 - 否则它将使用系统默认值,这可能不是你想要的。InputStreamReaderByteArrayOutputStreamtoString()

编辑:好的,所以你真的想使用 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包装在 a 中BufferedReader,然后您就离开了。

于 2009-06-25T19:04:32.120 回答
4

你可以使用 NIO,但这里没有真正的需要。正如 Jon Skeet 建议的那样:

public byte[] read(InputStream istream)
{
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  byte[] buffer = new byte[1024]; // Experiment with this value
  int bytesRead;

  while ((bytesRead = istream.read(buffer)) != -1)
  {
    baos.write(buffer, 0, bytesRead);
  }

  return baos.toByteArray();
}


// after the process is run, we call this method with the String
public void readLines(byte[] data)
{
  BufferedReader reader = new BufferedReader(new InputStreamReader(new ByteArrayInputStream(data)));
  String line;

  while ((line = reader.readLine()) != null)
  {
    // do stuff with line
  }
}
于 2009-06-25T19:42:45.023 回答
1

这是一个示例:

public class ByteBufferBackedInputStream extends InputStream {

    ByteBuffer buf;

    public ByteBufferBackedInputStream(ByteBuffer buf) {
        this.buf = buf;
    }

    public synchronized int read() throws IOException {
        if (!buf.hasRemaining()) {
            return -1;
        }
        return buf.get() & 0xFF;
    }

    @Override
    public int available() throws IOException {
        return buf.remaining();
    }

    public synchronized int read(byte[] bytes, int off, int len) throws IOException {
        if (!buf.hasRemaining()) {
            return -1;
        }

        len = Math.min(len, buf.remaining());
        buf.get(bytes, off, len);
        return len;
    }
}

你可以像这样使用它:

    String text = "this is text";   // It can be Unicode text
    ByteBuffer buffer = ByteBuffer.wrap(text.getBytes("UTF-8"));

    InputStream is = new ByteBufferBackedInputStream(buffer);
    InputStreamReader r = new InputStreamReader(is, "UTF-8");
    BufferedReader br = new BufferedReader(r);
于 2012-11-11T08:37:55.323 回答