哪个Java库提供base64编码/解码? [英] Which Java library provides base64 encoding/decoding?

查看:158
本文介绍了哪个Java库提供base64编码/解码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪个库用于base64编码/解码?我需要这个功能足够稳定以供生产使用。

I am wondering which library to use for base64 encoding/decoding? I need this functionality be stable enough for production use.

推荐答案

Java 9



使用Java 8解决方案。注意仍然可以使用DatatypeConverter,但它现在位于 java.xml.bind 模块中,需要包含该模块。

Java 9

Use the Java 8 solution. Note DatatypeConverter can still be used, but it is now within the java.xml.bind module which will need to be included.

module org.example.foo {
    requires java.xml.bind;
}



Java 8



Java 8现在提供 java。 util.Base64 用于编码和解码base64。

Java 8

Java 8 now provides java.util.Base64 for encoding and decoding base64.

编码

byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=

解码

byte[] decoded = Base64.getDecoder().decode("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// => hello world



Java 6和7



从Java 6开始,鲜为人知的类 <$ c $可以使用c> javax.xml.bind.DatatypeConverter 。这是JRE的一部分,不需要额外的库。

Java 6 and 7

Since Java 6 the lesser known class javax.xml.bind.DatatypeConverter can be used. This is part of the JRE, no extra libraries required.

编码

byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=  

解码

byte[] decoded = DatatypeConverter.parseBase64Binary("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, "UTF-8"));
// => hello world

这篇关于哪个Java库提供base64编码/解码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆