创建了Java zip文件但未打开,表示意外的文件末尾

day*_*mer 6 java gzip

我有一个Object

private String name;
private int age;
private String country;
// getters and setters
Run Code Online (Sandbox Code Playgroud)

和功能是

protected void write(@Nonnull final Document document, @Nonnull final OutputStream stream) throws PersistenceException {
        try {
            jaxbContext.createMarshaller().marshal(document, stream);
        } catch (final JAXBException e) {
            LOGGER.error(e.getMessage(), e);
            throw new PersistenceException("Failed to marshall document " + docment.getUniqueId() + ": " + e.getMessage(), e);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我把它转换成zip文件为

           ByteArrayOutputStream stream = new ByteArrayOutputStream();
           write(document, stream);
           GZIPOutputStream gzipOutputStream = new GZIPOutputStream(new FileOutputStream(new File(getOutputFilePath(document.getUniqueId()))));
           gzipOutputStream.write(stream.toByteArray());
Run Code Online (Sandbox Code Playgroud)

这会创建zip文件,但当我尝试打开它时,它会说

gzip: document.xml.gz: unexpected end of file
Run Code Online (Sandbox Code Playgroud)

我在这里做的不是什么?

Jon*_*Lin 12

您需要确保致电:

gzipOutputStream.flush();
Run Code Online (Sandbox Code Playgroud)

并最终

gzipOutputStream.close();
Run Code Online (Sandbox Code Playgroud)