import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import java.util.Base64;
public class ZipBase64Example {
public static void main(String[] args) {
String input = "abc123";
String encodedResult = zipEncode(input, true);
System.out.println("Compressed and Base64 Encoded String:");
System.out.println(encodedResult);
}
public static String zipEncode(String str, boolean isZip) {
String encodeStr = "";
try {
if (isZip) {
encodeStr = Base64.getEncoder().encodeToString(compress(str));
} else {
encodeStr = Base64.getEncoder().encodeToString(str.getBytes("UTF-8")).trim();
}
if (encodeStr != null) {
encodeStr = encodeStr.replaceAll("\r\n", "").replaceAll("\n", "");
}
} catch (Exception e) {
e.printStackTrace();
}
return encodeStr;
}
private static byte[] compress(String str) {
if (str == null) {
return null;
}
byte[] compressed;
ByteArrayOutputStream out = null;
ZipOutputStream zout = null;
try {
out = new ByteArrayOutputStream();
zout = new ZipOutputStream(out);
zout.putNextEntry(new ZipEntry("0"));
zout.write(str.getBytes("UTF-8"));
zout.closeEntry();
compressed = out.toByteArray();
} catch (IOException e) {
compressed = null;
e.printStackTrace();
} finally {
if (zout != null) {
try {
zout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (out != null) {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return compressed;
}
}