Domanda

Esiste un modo per leggere un ByteBuffer con un BufferedReader senza doverlo prima trasformare in una stringa? Voglio leggere un ByteBuffer abbastanza grande come righe di testo e per motivi di prestazioni voglio evitare di scriverlo sul disco. Chiamare toString su ByteBuffer non funziona perché la stringa risultante è troppo grande (genera java.lang.OutOfMemoryError: spazio heap Java). Avrei pensato che ci sarebbe qualcosa nell'API per avvolgere un ByteBuffer in un lettore adatto, ma non riesco a trovare nulla di adatto.

Ecco un esempio di codice abbreviato che illustra cosa sto facendo):

// 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
  }
}
È stato utile?

Soluzione

Non è chiaro il motivo per cui stai utilizzando un buffer di byte per iniziare. Se hai un InputStream e vuoi leggere delle righe, perché non usi semplicemente un InputStreamReader racchiuso in un BufferedReader? Qual è il vantaggio di coinvolgere NIO?

Chiamare toString() su ByteArrayOutputStream mi sembra una cattiva idea anche se tu avessi lo spazio per esso: meglio prenderlo come un array di byte e avvolgerlo in un ByteArrayInputStream e poi un <=> , se devi davvero avere un <=>. Se davvero vuoi chiamare <=>, almeno usa il sovraccarico che prende il nome della codifica dei caratteri da usare, altrimenti userà il sistema predefinito, che probabilmente non è quello che vuoi .

EDIT: Okay, quindi vuoi davvero usare NIO. Alla fine stai ancora scrivendo su <=>, quindi finirai con un BAOS con i dati al suo interno. Se vuoi evitare di fare una copia di tali dati, dovrai derivare da <=>, ad esempio in questo modo:

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);
    }
}

Quindi puoi creare il flusso di input, avvolgerlo in un <=>, avvolgerlo in un <=> e sei via.

Altri suggerimenti

Puoi usare NIO, ma qui non c'è davvero bisogno. Come ha suggerito 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
  }
}

Questo è un esempio:

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;
    }
}

E puoi usarlo in questo modo:

    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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top