java - How to get a byte array from FileInputStream without OutOfMemory error -
i have fileinputstream has 200mb of data. have retrieve bytes input stream.
i'm using below code convert inputstream byte array.
private byte[] convertstreamtobytearray(inputstream inputstream) { bytearrayoutputstream bos = new bytearrayoutputstream(); try { int i; while ((i = inputstream.read()) > 0) { bos.write(i); } } catch (ioexception e) { e.printstacktrace(); } return bos.tobytearray(); }
i'm getting outofmemory exception while coverting such large data byte array.
kindly let me know possible solutions convert inputstream byte array.
why want hold 200mb file in memory? going to byte array?
if going write outputstream, outputstream ready first, read inputstream chunk @ time, writing chunk outputstream go. you'll never store more chunk in memory.
eg:
public static void pipe(inputstream is, outputstream os) throws ioexception { int read = -1; byte[] buf = new byte[1024]; try { while( (read = is.read(buf)) != -1) { os.write(buf, 0, read); } } { is.close(); os.close(); } }
this code take 2 streams , pipe 1 other.
Comments
Post a Comment