java 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);
    }
}

输出:

hello world

通过Base64 将String转换成byte[]或者byte[]转换成String[Java 8]

可能你已经了解 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) );
    }
}

输出:

hello world

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

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

转载:https://www.cnblogs.com/keeplearnning/p/7003415.html

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐