Java中Base64的几种用法小结
作者:爱码少年 00fly.online
文章简要介绍了Java中Base64编码和解码的常见应用场景,包括字符串、文件、本地图片和网络图片的编码解码,并介绍了Java8及以上版本内置的java.util.Base64工具类的使用方法,需要的朋友可以参考下
一、简要概述
在 Java 中使用 Base64 编码和解码非常常见,尤其是在处理网络传输、加密数据、图片处理等场景。Java 8 及以上版本提供了内置的 java.util.Base64 工具类,非常方便使用。
二、几种用法
1、字符串编码解码
/**
* URL安全编码
*/
@Test
public void test1()
{
String input = RandomStringUtils.randomAlphanumeric(50);
String encoded = Base64.getUrlEncoder().encodeToString(input.getBytes());
log.info("{} --> {}", input, encoded);
// 解码
byte[] decodeBytes = Base64.getUrlDecoder().decode(encoded);
log.info(new String(decodeBytes));
}
2、文件编码解码
/**
* 安全编码文件
*
* @throws IOException
*/
@Test
public void testFile()
throws IOException
{
byte[] fileBytes = Files.readAllBytes(Paths.get(new ClassPathResource("log4j2.xml").getURI()));
String encoded = Base64.getUrlEncoder().encodeToString(fileBytes);
log.info("Encoded file: {}", encoded);
// 解码
byte[] decodeBytes = Base64.getUrlDecoder().decode(encoded);
log.info(new String(decodeBytes));
}
3、本地图片编码解码
/**
* 安全编码图片
*
* @throws IOException
*/
@Test
public void testPic()
throws IOException
{
// Paths相对路径为当前项目
byte[] fileBytes = Files.readAllBytes(Paths.get("src/main/resources/data/18.jpg"));
String encoded = Base64.getUrlEncoder().encodeToString(fileBytes);
log.info("Encoded file: {}", encoded);
// 解码
byte[] decodeBytes = Base64.getUrlDecoder().decode(encoded);
Files.write(Paths.get("/001.jpg"), decodeBytes);
}
4、网络图片编码解码
/**
* 安全编码图片
*
* @throws IOException
*/
@Test
public void testNetPic()
throws IOException
{
Resource resource = new UrlResource("https://i-blog.csdnimg.cn/direct/d4f0934d9ac041d583f81126fcc40f1d.png");
try (InputStream is = resource.getInputStream())
{
// 编码解码网络图片
String encoded = Base64.getUrlEncoder().encodeToString(IOUtils.toByteArray(is));
byte[] decodeBytes = Base64.getUrlDecoder().decode(encoded);
Files.write(Paths.get("/002.jpg"), decodeBytes);
}
}
到此这篇关于Java中Base64的几种用法小结的文章就介绍到这了,更多相关Java Base64用法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
