Writing billions of lines to text file in java
It sure sounds like you're running out of memory as you try to build (or allocate) the buffer. 


You need to figure out how big a buffer you can (or want to) use. You'll need to ask the system how much RAM it has, and how much is available, and make your buffer that large.
You might get a small boost by opening the file as explicitly write-only.
You'll need to flush the buffer as you go. Something shaped like this psudo-code might work:


free = system.free_ram();
use = hungry * free;
buffer = new bytes_buffer_to_file("filename", size=use);
try{
  current_buffer = 0;
  while(line = get_bytes_needing_to_be_written()){
    if(current_buffer + line.length &gt; use){
      buffer.flush();
      current_buffer = 0;
    }
    buffer.append(line);
    current_buffer += line.length;
  }
}
finally{
  buffer.flush();
  buffer.destroy();
}