user2725919
user2725919

Reputation: 307

Zipping XML into GZIPOutputStream

I am trying to use the StaX API to create some XML, save it in a FileOutputStream and put that stream inside a GZIPOutPutStream.

Clearly I am doing something wrong however because the following code outputs a corrupt file: hellow.xml.gz. I can open the zip file and see the xml file inside. However on extracting I get an error saying the file is broken.

The code works just file if I output to a text file rather than attempting to zip up the file with GZIPOutPutStream. How do I get the xml to write and compress into the gzip correctly?

public class Main {

    public static void main(String[] args) throws XMLStreamException, IOException {

        FileOutputStream outputStream = new FileOutputStream(new File("/home/user/hellow.xml.gz"));
        GZIPOutputStream outputStreamZip = new GZIPOutputStream(outputStream);
        XMLOutputFactory factory = XMLOutputFactory.newInstance();

        XMLStreamWriter writer = factory.createXMLStreamWriter(outputStreamZip, "UTF-8");

        writer.writeStartElement("WOOOOOOOOOOOOOOOOOOOOOOOOOOOOT");
        writer.writeStartElement("Lookup_Value_Record");
        writer.writeCharacters("Hello World");

        writer.writeEndElement();
        writer.writeEndElement();
        writer.writeEndDocument();

        writer.flush();
        writer.close();

    }
}

Upvotes: 1

Views: 799

Answers (1)

user2725919
user2725919

Reputation: 307

The answer was very very simple. I just needed to close the Gzip output stream.

outputStreamZip.close();

Upvotes: 1

Related Questions