java - Java:将字节字符串转换为字节数组
问题描述
我想将 my 转换byte[]
为 a String
,然后将其转换String
为 a byte[]
。
所以,
byte[] b = myFunction();
String bstring = b.toString();
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser);
bstring 给我[B@74e752bb
。
然后转换String
为byte[]
. 我没有按此顺序使用它,但这是一个示例。
我需要如何在 Java 中执行此操作?
解决方案
将 byte[] 转换为 String 时,应该使用这个,
new String(b, "UTF-8");
代替,
b.toString();
将字节数组转换为字符串时,应始终指定字符编码并在从字符串转换回字节数组时使用相同的编码。最好是使用 UTF-8 编码,因为它非常强大且紧凑,可以表示超过一百万个字符。如果您不指定字符编码,则可能会使用平台的默认编码,当从字节数组转换为字符串时,可能无法正确表示所有字符。
如果处理得当,你的方法应该写成这样,
public static void main(String args[]) throws Exception {
byte[] b = myFunction();
// String bstring = b.toString(); // don't do this
String bstring = new String(b, "UTF-8");
byte[] ser = bstring.getBytes("UTF-8");
/* Here the methode to convert the bstring to byte[], and call it ser */
String deser = new String(ser, "UTF-8");
}
推荐阅读
- php - 如何为 html 元素提供一个从 php 变量中获取的 ID?
- c# - 如何让我的 MSTest 像在我“升级”到新型项目文件之前那样在 Visual Studio 中实际运行?
- algorithm - 两个或多个 for 循环时间复杂度
- javascript - 在 Django ModelForm 中创建动态表单字段
- r - 我正在尝试按照创建自己的 R 包的指南说明在 Windows 10 上制作 rcpp 包
- android - 如何使用launchFragmentInHiltContainer将视图模型传递给片段
- arrays - 使用数组从json数组中获取数据?
- mysql - Ubuntu 的 MySQL 工作台中没有模式面板
- mongodb - 创建具有交替 IP 地址的服务器副本集
- php - 错误的 php 和 XML 声明只允许在文档的开头