0

I'm writing a simple program that retrieves XML data from an object, and parses it dynamically, based on user criteria. I am having trouble getting the XML data from the object, due to the format it is available in.

The object containing the XML returns the data as a byteArray of a zipFile, like so.

    MyObject data = getData();
    byte[] byteArray = data.getPayload(); 

//The above returns the byteArray of a zipFile

The way I checked this, is by writing the byteArray to a String

    String str = new String(byteArray); 

//The above returns a string with strange characters in it.

Then I wrote the data to a file.

    FileOutputStream fos = new FileOutputStream("new.txt");
    fos.write(byteArray);

I renamed new.txt as new.zip. When I opened it using WinRAR, out popped the XML.

My problem is that, I don't know how to do this conversion in Java using streams, without writing the data to a zip file first, and then reading it. Writing data to disk will make the software way too slow. Any ideas/code snippets/info you could give me would be really appreciated!! Thanks Also, if you need a better explanation from me, I'd be happy to elaborate.

As another option, I am wondering whether an XMLReader would work with a ZipInputStream as InputSource.

    ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
    ZipInputStream zis = new ZipInputStream(bis);
    InputSource inputSource = new InputSource(zis);
Klua
  • 11
  • 3

1 Answers1

3

A zip archive can contain several files. You have to position the zip stream on the first entry before parsing the content:

ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
ZipInputStream zis = new ZipInputStream(bis);
ZipEntry entry = zis.getNextEntry();
InputSource inputSource = new InputSource(new BoundedInputStream(zis, entry.getCompressedSize()));

The BoundedInputStream class is taken from Apache Commons IO (http://commons.apache.org/io)

Ed Staub
  • 15,480
  • 3
  • 61
  • 91
Emmanuel Bourg
  • 9,601
  • 3
  • 48
  • 76
  • Will I have to implement the XMLReader interface? Also, is there another easier option, which I am complete missing, to retrieve the xml file from the zip file? – Klua Jul 21 '11 at 20:05
  • I tried using the above code snippet. ZipEntry entry is null. – Klua Jul 21 '11 at 20:14
  • Are you sure it's a zip file and not a gzip file? In this case a GZIPInputStream would be more appropriate. – Emmanuel Bourg Jul 21 '11 at 21:03
  • Hi Emmanuel, You, sir, are a genius! Unfortunately, the Java API doesn't throw a descriptive exception, and since WinRAR was able to open it as zip, I assumed it was the right format. Thanks for this, I will know how to solve this problem in the future because of you! – Klua Jul 21 '11 at 22:30