如何将字符串转换为 GZIP Base64 字符串?

发布于 2024-12-11 08:05:45 字数 158 浏览 0 评论 0原文

我一直在尝试弄清楚如何使用 GZIPOutputStream 等,但在理解它们方面没有成功。我想做的就是将一串字符 - “一串字符”转换为 GZIP Base64 格式。我该怎么做?

通过 GZIP Base64 格式,我的意思是首先使用 GZIP 压缩字符串,然后转换为 Base64。

I've been trying to figure out using GZIPOutputStream's and the like but have had no success with understanding them. All I want to do is convert a string of characters - "A string of characters" into a GZIP Base64 format. How can I do this?

By GZIP Base64 format, I mean the string is first compressed using GZIP, then converted into Base64.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

夏雨凉 2024-12-18 08:05:45

使用 Apache Commons 编解码器 Base64OutputStream

下面是一个示例类:

import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64OutputStream;

public class Test {
    public static void main(String[] args) {
        String text = "a string of characters";
        try {
            Base64OutputStream b64os = new Base64OutputStream(System.out);
            GZIPOutputStream gzip = new GZIPOutputStream(b64os);
            gzip.write(text.getBytes("UTF-8"));
            gzip.close();
            b64os.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

输出:

H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA

在 Linux 下,您可以确认这适用于:(

echo 'H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA' | base64 -d | gunzip

请注意,在 OSX 上,您应该使用 base64 -D 而不是 base64 -d在上面的命令中)

输出:

a string of characters

Use the Apache Commons Codec Base64OutputStream.

Here's a sample class:

import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64OutputStream;

public class Test {
    public static void main(String[] args) {
        String text = "a string of characters";
        try {
            Base64OutputStream b64os = new Base64OutputStream(System.out);
            GZIPOutputStream gzip = new GZIPOutputStream(b64os);
            gzip.write(text.getBytes("UTF-8"));
            gzip.close();
            b64os.close();
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

Which outputs:

H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA

Under Linux, you can confirm this works with:

echo 'H4sIAAAAAAAAAEtUKC4pysxLV8hPU0jOSCxKTC5JLSoGAOP+cfkWAAAA' | base64 -d | gunzip

(Please note that on OSX, you should use base64 -D instead of base64 -d in the above command)

Which outputs:

a string of characters
弄潮 2024-12-18 08:05:45

Java 9

示例:

public static void main(String[] args) throws IOException {
    byte[] original = "string".getBytes(StandardCharsets.UTF_8);

    // encode
    byte[] gzipToBase64 = encodeToBase64(encodeToGZIP(original));
    System.out.println(new String(gzipToBase64));
    //H4sIAAAAAAAAACsuKcrMSwcAqbK+ngYAAAA=

    // decode
    byte[] fromBase64Gzip = decodeFromGZIP(decodeFromBase64(gzipToBase64));
    System.out.println(Arrays.equals(original, fromBase64Gzip)); //true
}
public static byte[] decodeFromBase64(byte[] arr) {
    return Base64.getDecoder().decode(arr);
}

public static byte[] encodeToBase64(byte[] arr) {
    return Base64.getEncoder().encode(arr);
}
public static byte[] decodeFromGZIP(byte[] arr) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(arr);
    GZIPInputStream gzip = new GZIPInputStream(bais);
    return gzip.readAllBytes();
}

public static byte[] encodeToGZIP(byte[] arr) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(baos);
    gzip.write(arr);
    gzip.finish();
    return baos.toByteArray();
}

另请参阅:编码为 Base64 Java

Java 9

Example:

public static void main(String[] args) throws IOException {
    byte[] original = "string".getBytes(StandardCharsets.UTF_8);

    // encode
    byte[] gzipToBase64 = encodeToBase64(encodeToGZIP(original));
    System.out.println(new String(gzipToBase64));
    //H4sIAAAAAAAAACsuKcrMSwcAqbK+ngYAAAA=

    // decode
    byte[] fromBase64Gzip = decodeFromGZIP(decodeFromBase64(gzipToBase64));
    System.out.println(Arrays.equals(original, fromBase64Gzip)); //true
}
public static byte[] decodeFromBase64(byte[] arr) {
    return Base64.getDecoder().decode(arr);
}

public static byte[] encodeToBase64(byte[] arr) {
    return Base64.getEncoder().encode(arr);
}
public static byte[] decodeFromGZIP(byte[] arr) throws IOException {
    ByteArrayInputStream bais = new ByteArrayInputStream(arr);
    GZIPInputStream gzip = new GZIPInputStream(bais);
    return gzip.readAllBytes();
}

public static byte[] encodeToGZIP(byte[] arr) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(baos);
    gzip.write(arr);
    gzip.finish();
    return baos.toByteArray();
}

See also: Encoding as Base64 in Java

岛歌少女 2024-12-18 08:05:45

这是此答案的变体,但没有弃用的内容并使用 Vavr Try

public static Try<String> compress(String input) {
  return Try.of(() -> {
    ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
    GZIPOutputStream zos = new GZIPOutputStream(rstBao);
    zos.write(input.getBytes(StandardCharsets.UTF_8));
    zos.close();
    return Base64.encodeBase64String(rstBao.toByteArray());
   });

public static Try<String> decompress(String input) {
  return Try.of(() -> IOUtils.toString(new GZIPInputStream(
    new ByteArrayInputStream(Base64.decodeBase64(input))),        
      StandardCharsets.UTF_8));
  }
}

// unit test
@Test
public void testStringCompression() {
  var data = "I finally rest. And watch the sun rise on a grateful universe. The hardest choices require the strongest wills.";
  var cs = Utilities.compress(data);
  assertThat(cs.isSuccess());
  var us = Utilities.decompress(cs.get());
  assertThat(us.isSuccess() && us.get().equals(data));
}

This is a variation of this answer but without the deprecated stuff and using Vavr Try:

public static Try<String> compress(String input) {
  return Try.of(() -> {
    ByteArrayOutputStream rstBao = new ByteArrayOutputStream();
    GZIPOutputStream zos = new GZIPOutputStream(rstBao);
    zos.write(input.getBytes(StandardCharsets.UTF_8));
    zos.close();
    return Base64.encodeBase64String(rstBao.toByteArray());
   });

public static Try<String> decompress(String input) {
  return Try.of(() -> IOUtils.toString(new GZIPInputStream(
    new ByteArrayInputStream(Base64.decodeBase64(input))),        
      StandardCharsets.UTF_8));
  }
}

// unit test
@Test
public void testStringCompression() {
  var data = "I finally rest. And watch the sun rise on a grateful universe. The hardest choices require the strongest wills.";
  var cs = Utilities.compress(data);
  assertThat(cs.isSuccess());
  var us = Utilities.decompress(cs.get());
  assertThat(us.isSuccess() && us.get().equals(data));
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文