Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 585
Santiago molano perdomo Avatar asked Jan 21 '26 12:01

Santiago molano perdomo


1 Answers

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.

like image 112
Cameron Avatar answered Jan 24 '26 02:01

Cameron



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!