How to add ZipEntry using XZ for Java

470 views Asked by At

I'm zipping some json files using the standard ZipOutputStream

ObjectMapper objectMapper = new ObjectMapper();
try (ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(outputFile + ".zip"))) {
    out.putNextEntry(new ZipEntry(jsonFileName + ".json"));
    objectMapper.writeValue(out, jsonDataList);
}

Output:

outputFile.zip\jsonFileName.json => jsonDataList contents

I want to change it from .zip to .7z or .xz I'm currently tring out XZ for Java (https://tukaani.org/xz/java.html)

ObjectMapper objectMapper = new ObjectMapper();
try (XZOutputStream out = new XZOutputStream(Files.newOutputStream(outputFile + ".xz"), new LZMA2Options())) {
    objectMapper.writeValue(out, jsonDataList);
    out.finish();
}

Output:

outputFile.xz\DataTypeOfJsonDataList => jsonDataList contents

It works in that there are no errors, a .xz file is created, and it does contain one .json file (although the file name is just the data type of "jsonDataList" minus the ".json" extension)

How do I specify the file name of the content? XZOutputStream doesn't seem to have a way to add a ZipEntry.

2

There are 2 answers

0
Mark Adler On BEST ANSWER

xz is not 7z. 7z is a compressed archive format, which means it can contain multiple files as well as a directory structure. xz is a single-file compression format. It can be used in combination with the uncompressed tar archive format to make a different compressed archive format, .tar.xz.

0
sikidhart On

Thanks to Boris the Spider and Mark Adler for putting me on the right track.

I was able to add an entry into a 7z archive using the org.apache.commons.compress.archivers.sevenz package

SevenZOutputFile sevenZOutput = new SevenZOutputFile(outputFile + ".7z");
SevenZArchiveEntry entry = sevenZOutput.createArchiveEntry(jsonFile, jsonFileName + ".json");
sevenZOutput.putArchiveEntry(entry);
sevenZOutput.write(objectMapper.writeValueAsBytes(data));
sevenZOutput.closeArchiveEntry();
sevenZOutput.close();