我需要一个解决方案,将字符串转换为字节数组没有这样的改变:
输入:
的String =测试;
输出:
的String =测试;
byte []的B =测试;
当我使用
s.getBytes();
![excel函数实例教程 单 双字节字符转换](https://p.xsw88.cn/allimgs/daicuo/20230904/7751.png)
则答复
[B @ 428b76b8
但我想的答复是
测试
解决方案
您应该始终确保序列化和反序列化使用的是相同的字符集,这个映射字符字节序列的,反之亦然。默认情况下String.getBytes()和新的字符串(字节),使用它可以是设置特定的默认字符集。
需要使用getBytes(字符集)重载
字节[]字节= s.getBytes(Charset.forName(UTF-8));
使用新的字符串(字节字符集)构造
字符串andBackAgain =新的字符串(字节,Charset.forName(UTF-8));
此外Java 7中添加了java.nio.charset.StandardCharsets类,所以您不必再使用狡猾的字符串常量
字节[]字节= s.getBytes(StandardCharsets.UTF_8);
字符串andBackAgain =新的字符串(字节,StandardCharsets.UTF_8);
I need a solution to convert String to byte array without changing like this:
Input:
String s="Test";
Output:
String s="Test";
byte[] b="Test";
When I use
s.getBytes();
then the reply is
"[B@428b76b8"
but I want the reply to be
"Test"
解决方案
You should always make sure serialization and deserialization are using the same character set, this maps characters to byte sequences and vice versa. By default String.getBytes() and new String(bytes) uses the default character set which could be Locale specific.
Use the getBytes(Charset) overload
byte[] bytes = s.getBytes(Charset.forName("UTF-8"));
Use the new String(bytes, Charset) constructor
String andBackAgain = new String(bytes, Charset.forName("UTF-8"));
Also Java 7 added the java.nio.charset.StandardCharsets class, so you don't need to use dodgy String constants anymore
byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
String andBackAgain = new String(bytes, StandardCharsets.UTF_8);
相关推荐
最新文章