美文网首页Java部分
java中String与byte数组互换

java中String与byte数组互换

作者: Geroge1226 | 来源:发表于2021-07-02 16:07 被阅读0次

1、说明

java中String数据是以char[]存储, 而我们在文件读取到内存中经常会已byte字节流形式读取。读取处理完数据,在返回给用户端String形式。这里会涉及到String数据格式与byte[]格式换换情况。

2、String转byte[]

打开jdkString提供的方法中发现:getByte() 方法可以实现

image.png
 String memberId = "susdfwt144642";
 memberId.getBytes();

端点调试,我们发现byte[]长度13位,值存的是字符对应ASCII码。如下图:s --> 115


image.png

3、byte[] 转String

打开jdk提供的String方法,发现String构造函数中可以直接传入byte[],如下图:

image.png
 String memberId = "susdfwt144642";
 byte[] memberIds = memberId.getBytes();
 String ok = new String(memberIds);
 System.out.println(ok);

运行结果:

Connected to the target VM, address: '127.0.0.1:62887', transport: 'socket'
susdfwt144642

注意:互换过程中最好指定编码。防止编码不一致出现乱码。

相关文章

网友评论

    本文标题:java中String与byte数组互换

    本文链接:https://www.haomeiwen.com/subject/zmgeultx.html