Writing large files using BufferedOutputStream

user1229894 picture user1229894 · Feb 24, 2012 · Viewed 26k times · Source

I am trying read and write large files (larger than 100 MBs) using BufferedInputStream & BufferedOutputStream. I am getting Heap Memory issue & OOM exception.
The code looks like :

BufferedInputStream buffIn = new BufferedInputStream(iStream);
/** iStream is the InputStream object  **/

BufferedOutputStream buffOut=new BufferedOutputStream(new FileOutputStream(file));
byte []arr = new byte [1024 * 1024];
int available  = -1;
while((available = buffIn.read(arr)) > 0) {   
    buffOut.write(arr, 0, available); 
}      
buffOut.flush();
buffOut.close();        

My question is when we use the BufferedOutputStreeam is it holding the memory till the full file is written out ?
What is the best way to write large files using BufferedOutputStream?

Answer

jtahlborn picture jtahlborn · Feb 24, 2012

there is nothing wrong with the code you have provided. your memory issues must lie elsewhere. the buffered streams have a fixed memory usage limit.

the easiest way to determine what has caused an OOME, of course, is to have the OOME generate a heap dump and then examine that heap dump in a memory profiler.