/* from: https://hacpai.com/article/1481701879422/comment/1481871510461 */
import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.util.Base64; public static String lzma(final String str) throws IOException { if (str == null || "".equals(str)) { return str; } final SevenZip.Compression.LZMA.Encoder encoder = new SevenZip.Compression.LZMA.Encoder(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayInputStream in = new ByteArrayInputStream(str.getBytes()); try { encoder.SetEndMarkerMode(false); encoder.WriteCoderProperties(out); final long fileSize = in.available(); for (int i = 0; i < 8; i++) { out.write((int) (fileSize >>> (8 * i)) & 0xFF); } encoder.Code(in, out, -1, -1, null); final byte[] compressed = out.toByteArray(); byte[] b64 = Base64.getEncoder().encode(compressed); return new String(b64, "UTF-8"); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } public static String unlzma(final String compressedStr) throws IOException { if (null == compressedStr || "".equals(compressedStr)) { return compressedStr; } final SevenZip.Compression.LZMA.Decoder decoder = new SevenZip.Compression.LZMA.Decoder(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); final ByteArrayInputStream in = new ByteArrayInputStream(Base64.getDecoder().decode(compressedStr)); try { final int propertiesSize = 5; final byte[] properties = new byte[propertiesSize]; if (in.read(properties, 0, propertiesSize) != propertiesSize) { throw new IOException("input .lzma file is too short"); } if (!decoder.SetDecoderProperties(properties)) { throw new IOException("Incorrect stream properties"); } long outSize = 0; for (int i = 0; i < 8; i++) { final int v = in.read(); if (v < 0) { throw new IOException("Can't read stream size"); } outSize |= ((long) v) << (8 * i); } if (!decoder.Code(in, out, outSize)) { throw new IOException("Error in data stream"); } return out.toString("UTF-8"); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } }