I have a method which I have an array of String objects which I need to write to a ByteArrayOutputStream which later on I will write into a ZipOutputStream.
Here is my code.
// SAVE THE STRING AS A BYTE ARRAY IN MEMORY INSTEAD OF CREATING AND SAVING TO A NEW FILE
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream byteOut = new DataOutputStream(baos);
byte[] data;
if (i == 1) {
if (nodeStringArray != null) {
for (String s : nodeStringArray) {
byteOut.write(s.getBytes("UTF-8"));
}
}
} else {
data = stringArray.get(i).getBytes("UTF-8");
byteOut.write(data);
}
byteOut.close();
byte[] input = baos.toByteArray();
ZipEntry entry = new ZipEntry(fileName);
entry.setSize(input.length);
zos.putNextEntry(entry);
zos.write(input);
zos.closeEntry();
The issue is, and I have only received on crash report for it, I am getting an OutOfMemoryError
on the line that reads byteOut.write(s.getBytes("UTF-8"));
Anyone know of a better way of doing this or can see if I am doing something wrong?
IDEA
Could I put a try catch statement around the problem and when it happens call byteOut.flush()
?
Thanks in advance
You are making to many copies of the data, and this is causing you to run out of memory.
You should be directly writing into your ZipOutputStream
in your first loop.
ZipEntry entry = new ZipEntry(fileName);
zos.putNextEntry(entry);
for (String s : nodeStringArray) {
zos.write(s.getBytes("UTF-8"));
}
zos.closeEntry();