problems to write big String to a file

I am trying to write a String in Base64, this String represents a PDF file,

for (int i = 0; i < 500; i++) {
        cedula++;
        escribirArchivo.escribirInfoEnElArchivo(data1.append(pdf).append(",").append(cedula).toString());
        escribirArchivo.escribirInfoEnElArchivo(data2.append(pdf2).append(",").append(cedula).toString());
        escribirArchivo.escribirInfoEnElArchivo(data3.append(pdf3).append(",").append(cedula).toString());
    }

and this is my method to write a file

  public void escribirInfoEnElArchivo( String infoToWrite) {
    try {
        fileWriter.write(infoToWrite + "\n");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

this consume around 2-3GB of ram in some point I ran out of memory and throws and error with Heap memory, how can I perform this in a better way?

Upvotes: 3

Views: 64

Answers (1)

Cameron
Cameron

Reputation: 1590

As azurefrog said in his comment, creating the entire string first before writing it is massively expensive for memory. Instead of building the string and passing that to escribirInfoEnElArchivo(), just pass the pdf and use the file writer to write it from there. If you need to append additional information, you can do that in escribirInfoEnElArchivo() after you write the pdf.

Upvotes: 1

Related Questions