我有一个Base64编码的图像。Java中最好的解码方法是什么?希望只使用Sun Java 6中包含的库。
当前回答
给出一个javax.xml.bind.DatatypeConverter的测试编码/解码示例,使用方法parseBase64Binary()和printBase64Binary()引用@jeremy-ross和@nightfirecat answer。
@Test
public void EncodeDecode() {
//ENCODE
String hello = "Hello World";
byte[] helloBytes = hello.getBytes(StandardCharsets.UTF_8);
String encodedHello = DatatypeConverter.printBase64Binary(helloBytes);
LOGGER.info(hello + " encoded=> " + encodedHello);
//DECODE
byte[] encodedHelloBytes = DatatypeConverter.parseBase64Binary(encodedHello);
String helloAgain = new String(encodedHelloBytes, StandardCharsets.UTF_8) ;
LOGGER.info(encodedHello + " decoded=> " + helloAgain);
Assert.assertEquals(hello, helloAgain);
}
结果:
INFO - Hello World encoded=> SGVsbG8gV29ybGQ=
INFO - SGVsbG8gV29ybGQ= decoded=> Hello World
其他回答
我知道现在回答有点晚了,但对于JDK 8及以上版本。
Base64.getEncoder().encodeToString("anyStringData".getBytes());
Base64.getDecoder().decode("encodedData");
进口
import java.util.Base64;
请参考此OracleDocs !
番石榴现在内置了Base64解码。
使用BaseEncoding.base64 () .decode ()
至于处理输入使用中可能出现的空白
BaseEncoding.base64 () .decode (CharMatcher.WHITESPACE.removeFrom(…));
有关更多信息,请参阅此讨论
给出一个javax.xml.bind.DatatypeConverter的测试编码/解码示例,使用方法parseBase64Binary()和printBase64Binary()引用@jeremy-ross和@nightfirecat answer。
@Test
public void EncodeDecode() {
//ENCODE
String hello = "Hello World";
byte[] helloBytes = hello.getBytes(StandardCharsets.UTF_8);
String encodedHello = DatatypeConverter.printBase64Binary(helloBytes);
LOGGER.info(hello + " encoded=> " + encodedHello);
//DECODE
byte[] encodedHelloBytes = DatatypeConverter.parseBase64Binary(encodedHello);
String helloAgain = new String(encodedHelloBytes, StandardCharsets.UTF_8) ;
LOGGER.info(encodedHello + " decoded=> " + helloAgain);
Assert.assertEquals(hello, helloAgain);
}
结果:
INFO - Hello World encoded=> SGVsbG8gV29ybGQ=
INFO - SGVsbG8gV29ybGQ= decoded=> Hello World
特别是在通用Codec:类Base64解码(byte[]数组)或编码(byte[]数组)
从Java 8开始,就有了官方支持的用于Base64编码和解码的API。 随着时间的推移,这可能会成为默认的选择。
该API包括java.util类。Base64及其嵌套类。它支持三种不同的风格:基本的、URL安全的和MIME。
使用“基本”编码的示例代码:
import java.util.Base64;
byte[] bytes = "Hello, World!".getBytes("UTF-8");
String encoded = Base64.getEncoder().encodeToString(bytes);
byte[] decoded = Base64.getDecoder().decode(encoded);
String decodedStr = new String(decoded, StandardCharsets.UTF_8);
java.util的文档。Base64还包括一些配置编码器和解码器的方法,以及使用不同的类作为输入和输出(字节数组,字符串,ByteBuffers, java。io流)。
推荐文章
- 如何在java中格式化持续时间?(如格式H:MM:SS)
- urlencoder .encode(字符串)已弃用,我应该使用什么代替?
- javax.transaction.Transactional vs . org.springframework.transaction.annotation.Transactional
- Java 8接口方法中不允许“同步”的原因是什么?
- 如何找到Java堆大小和内存使用(Linux)?
- 使用Enum实现单例(Java)
- RabbitMQ与通道和连接之间的关系
- buildSessionFactory()配置方法在Hibernate中已弃用?
- Spring MVC -如何获得所有的请求参数在一个地图在Spring控制器?
- 如何在Java中按两个字段排序?
- 文件之间的差异。路径中的分隔符和斜杠
- 在方法参数中使用NotNull注释
- Spring MVC中处理可选参数的@RequestParam
- Tomcat:如何查找正在运行的Tomcat版本?
- “java”、“javaw”和“javaws”之间有什么区别?