zoukankan      html  css  js  c++  java
  • 通过Base64 将String转换成byte[]或者byte[]转换成String[Java 8]

    通过用例学习Java中的byte数组和String互相转换,这种转换可能在很多情况需要,比如IO操作,生成加密hash码等等。

    除非觉得必要,否则不要将它们互相转换,他们分别代表了不同的数据,专门服务于不同的目的,通常String代表文本字符串,byte数组针对二进制数据

    通过String类将String转换成byte[]或者byte[]转换成String
    用String.getBytes()方法将字符串转换为byte数组,通过String构造函数将byte数组转换成String

    注意:这种方式使用平台默认字符集

    package com.bill.example;
     
    public class StringByteArrayExamples 
    {
        public static void main(String[] args) 
        {
            //Original String
            String string = "hello world";
             
            //Convert to byte[]
            byte[] bytes = string.getBytes();
             
            //Convert back to String
            String s = new String(bytes);
             
            //Check converted string against original String
            System.out.println("Decoded String : " + s);
        }
    }
    

    可能你已经了解 Base64 是一种将二进制数据编码的方式,正如UTF-8和UTF-16是将文本数据编码的方式一样,所以如果你需要将二进制数据编码为文本数据,那么Base64可以实现这样的需求

    从Java 8 开始可以使用Base64这个类

    import java.util.Base64;
    public class StringByteArrayExamples 
    {
        public static void main(String[] args) 
        {
            //Original byte[]
            byte[] bytes = "hello world".getBytes();
             
            //Base64 Encoded
            String encoded = Base64.getEncoder().encodeToString(bytes);
             
            //Base64 Decoded
            byte[] decoded = Base64.getDecoder().decode(encoded);
             
            //Verify original content
            System.out.println( new String(decoded) );
        }
    }
    

    总结
    在byte[]和String互相转换的时候你应该注意输入数据的类型

    当使用String类的时候,将String作为输入类型
    当使用Base64类的时候,使用byte数组作为输入类型



    作者:cchilei

    -------------------------------------------

    个性签名:竹杖芒鞋轻胜马 一蓑烟雨任平生

    如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!

  • 相关阅读:
    Linux常用命令
    Spring Boot☞ 多数据源配置(二):Spring-data-jpa
    好用的Markdown编辑器一览
    Spring Boot☞ 使用Spring-data-jpa简化数据访问层
    谈谈Spring 注入properties文件总结
    Spring Boot☞ 统一异常处理
    Spring Boot☞ 使用velocity渲染web视图
    Spring Boot☞ 使用freemarker模板引擎渲染web视图
    静态联编与动态联编
    C++ 模板元编程 学习笔记
  • 原文地址:https://www.cnblogs.com/cchilei/p/15393722.html
Copyright © 2011-2022 走看看