0

When I use a very large file, the error happens out of memory, no way to treat this problem, or why not be happening in the code below?

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    //10*1024 = 10KB
    byte[] byteBuffer   = new byte[20*2048]; 

    int i = Integer.MAX_VALUE;
    while ((i = is.read(byteBuffer, 0, byteBuffer.length)) > 0) {

        baos.write(byteBuffer, 0, i);

    }

    return baos.toByteArray(); 
  • 1
    refer to [This SO Post](http://stackoverflow.com/questions/236861/how-do-you-determine-the-ideal-buffer-size-when-using-fileinputstream). That buffer size is not about your file size – Randyka Yudhistira Feb 26 '15 at 02:40

1 Answers1

1

ByteArrayOutputStream definition "A specialized OutputStream for class for writing content to an (internal) byte array. As bytes are written to this stream, the byte array may be expanded to hold more bytes. When the writing is considered to be finished, a copy of the byte array can be requested from the class."

You are writing Integer.MAX_VALUE * 10240 bytes to memory.

You may want to change the title to "Out of memory when writing to an in-memory stream"

Tarik
  • 10,810
  • 2
  • 26
  • 40