Java:将字节字符串转换为字节数组
我想将我的Java:将字节字符串转换为字节数组,java,arrays,byte,Java,Arrays,Byte,我想将我的字节[]转换为字符串,然后将该字符串转换为字节[] 所以 bstring给了我[B@74e752bb 然后将字符串转换为字节[]。我不是按这个顺序使用它,但这是一个示例 在Java中如何执行此操作?在将字节[]转换为字符串时,应使用 new String(b, "UTF-8"); 而不是 b.toString(); 当您将字节数组转换为字符串时,应始终指定字符编码,并在从字符串转换回字节数组时使用相同的编码。最好使用UTF-8编码,因为UTF-8编码非常强大且紧凑,可以表示超过一百
字节[]
转换为字符串
,然后将该字符串
转换为字节[]
所以
bstring给了我[B@74e752bb
然后将字符串
转换为字节[]
。我不是按这个顺序使用它,但这是一个示例
在Java中如何执行此操作?在将字节[]转换为字符串时,应使用
new String(b, "UTF-8");
而不是
b.toString();
当您将字节数组转换为字符串时,应始终指定字符编码,并在从字符串转换回字节数组时使用相同的编码。最好使用UTF-8编码,因为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");
}
String string = "Your String";
byte[] bytesFromString = string.getBytes(); // get bytes from a String
String StringFromByteArray = new String(bytesFromString); // get the String from a byte array
我不是专家,但您应该尝试“Byte”类提供的方法,如果需要,还可以尝试一些循环。尝试
Byte b=Byte.parseByte(String s)
将字符串转换为字节,尝试String s=Byte.toString(Byte b)
将字节转换为字符串。希望这有帮助:)。您可以这样做
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");
}
String string = "Your String";
byte[] bytesFromString = string.getBytes(); // get bytes from a String
String StringFromByteArray = new String(bytesFromString); // get the String from a byte array
为什么不
newstring(b)
那么bstring.getBytes()
呢?看看这里:@nullpointer因为我在另一个类中使用了b,那么ser的东西…我只想有一个保存方法来散列字符串,将其保存在yaml文件中,我可以解密它。如果你想保存byte[]事实上,在某些yaml文件中,您可以使用FileOutputStream将字节写入文件。我不确定您所说的“保存方式到哈希”是什么意思。您能详细说明一下吗?使用b.toString()将字节[]转换为字符串可能不会给您提供特定的字符串。对不起,我的意思是:它可以工作,但我想保存字节[]在yaml文件中以安全的方式保存,现在我只保存旧字符串。如何在yaml文件中以安全的方式保存它?请查看是否可以使用base64对字节数组进行编码,因为这将提供字节数组的物理可打印字符串版本。