1

I am creating multiple files from String's.

For example 4 strings; one in xml, and 3 csv format.

My question is do I have to first save these String's into a file before then reading it and then writing out to the ZipOutputStream? Just seems like a bit of a waste really.

Thanks in advance

StuStirling
  • 15,601
  • 23
  • 93
  • 150
  • Very similar question: http://stackoverflow.com/questions/357851/in-java-how-to-zip-file-from-byte-array – JeffS Nov 02 '12 at 15:46
  • http://stackoverflow.com/questions/9766420/how-to-send-zip-file-without-creating-it-on-physical-location This link may help – Rejinderi Nov 02 '12 at 15:46

1 Answers1

2

So here is my solution for saving multiple files without having to create physical files before. Be careful of string size.

for (int i =0; i <stringArray.size();i++) {
                String outString = stringArray.get(i);
                String fileName = null;
                if (i == 0) {
                    fileName = "StringOne.xml";

                } else if (i == 1) {
                    fileName = "StringTwo.csv";
                } else if (i ==2) {
                    fileName = "StringThree.csv";
                } else if (i == 3) {
                    fileName = "StringFour.csv";
                }
                Log.d("ZipCreation", "Creating "+fileName);
                // 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 = 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();
            }

Hope this helps someone

StuStirling
  • 15,601
  • 23
  • 93
  • 150