In this post, I am going to explain how to compress and decompress a string in Java.
Dependency used
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.21</version>
</dependency>
Below utility class use Apache Commons Compress for compression and decompression of strings.
StringCompressor.java
package com.sample.app.util;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.compress.utils.IOUtils;
public class StringCompessor {
public static String compress(String inputString) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try (OutputStream os = new CompressorStreamFactory()
.createCompressorOutputStream(CompressorStreamFactory.GZIP, baos)) {
os.write(inputString.getBytes(StandardCharsets.UTF_8));
}
return new String(baos.toByteArray(), StandardCharsets.ISO_8859_1);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String decompress(String compressedString) {
try {
byte[] compressedBytes = compressedString.getBytes(StandardCharsets.ISO_8859_1);
try (InputStream is = new CompressorStreamFactory().createCompressorInputStream(
CompressorStreamFactory.GZIP, new ByteArrayInputStream(compressedBytes))) {
byte[] decompressedBytes = IOUtils.toByteArray(is);
return new String(decompressedBytes, StandardCharsets.UTF_8);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
The compress method uses the Apache Commons Compress library to compress the input string using the GZIP compression format and returns the compressed string.
The decompress method decompresses the compressed string back to its original form.
As you observe the above snippet, Application converts the output stream to a string using the ISO_8859_1 while compressing, it is required to handle any potential encoding issues that might occur when dealing with binary data in certain environments.
App.java
package com.sample.app;
import java.io.IOException;
import org.apache.commons.compress.compressors.CompressorException;
import com.sample.app.util.StringCompessor;
public class App {
public static void main(String[] args) throws IOException, CompressorException {
String str = "Hello world Hello world Hello world Hello world";
String compressedString = StringCompessor.compress(str);
String decompressedString = StringCompessor.decompress(compressedString);
System.out.println("str : " + str);
System.out.println("compressedString : " + compressedString);
System.out.println("decompressedString : " + decompressedString);
}
}
You may like
Read pkcs12 certificate information in Java
How to Get Client Certificate from HttpServletRequest
Programmatically import certificate to cacerts file in Java
No comments:
Post a Comment