Base64 to byte array decode optimization - Java

I'm trying to decode a pdf in base64 to a byte array in an Android app. here's my code:

byte[] documentByte = Base64.decode(pdfBase64, Base64.DEFAULT);

Which works ok for most of the cases, but I've received a crash report in which seems it is going out of memory. Also, this operation is done a lot of times when starting the app (I have a list with around 500 documents) so I think that, even for the devices that don't crash, it will be good to optimize this operation somehow.

Reading about it I've found that, when encoding, some people divide the byte array to not store it completely at memory, but I don't know if it can be done decoding.

Is there any way to improve performance for this operation (and try to avoid the memory problem)?

Upvotes: 3

Views: 1098

Answers (1)

Óscar
Óscar

Reputation: 726

I would suggest you don't load the whole base64 string into memory. Use InputStream to load portion of data in the byte array, decode base64 from a byte array and append the result to a cache file, like that:

        try {
            InputStream in = new ByteArrayInputStream(base64.getBytes());
            FileOutputStream out = new FileOutputStream(resultPath);
            while (in.available() > 0) {
                byte[] buffer = new byte[1024];
                in.read(buffer);

                byte[] decoded = Base64.decode(buffer, Base64.DEFAULT);
                out.write(decoded, 0, decoded.length);
            }
        } catch (FileNotFoundException e) {
        } catch (IOException e) {}

Upvotes: 2

Related Questions