문제

는 방법이 있을 읽의 bytebuffer 로 BufferedReader 지 않고 그것을 설정하는 첫 번째 문자열?내가 원하는 읽기를 통해 상당히 큰의 bytebuffer 으로 라인의 텍스트와 성능을 위해서 내가를 피하려고 그것을 작성하여 디스크에 있습니다.전화 toString 에서의 bytebuffer 작동하지 않기 때문에 결과 문자열은 너무 큰(가 발생 java.랭.의 메모리 부족: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?는 무엇인 혜택을 받고 NIO 관련된?

전화 toString()ByteArrayOutputStream 같은 소리가 나쁜 생각이 나더라도 그것을 위해 공간:을 얻을 수있는 더 나은 그것은 바이트 배열로에 포장 ByteArrayInputStream 다음 InputStreamReader, 는 경우에,당신은 정말이 ByteArrayOutputStream.는 경우 부르고 싶 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, 과할 수 없습니다.

다른 팁

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

이것은 샘플입니다.

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top