简体   繁体   English

使用字符串而不是字节数组java

[英]Using string instead array of bytes java

Can I use string instead array of bytes made with new String(bytes)? 我可以使用字符串代替由新String(bytes)构成的字节数组吗? I whant to save them to database. 我希望将它们保存到数据库。 In bytes I have calculated md5 hash. 我以字节为单位计算了md5哈希值。

No, a String is not suitable as a container for arbitrary bytes. 不, String不适合作为任意字节的容器。

The String(byte[] bytes) constructor will interpret the array that you pass to it and convert it to characters, using the default character encoding of your system. String(byte[] bytes)构造函数将解释您传递给它的数组,并使用系统的默认字符编码将其转换为字符。 This might throw an exception if the byte array contains a sequence of bytes which is not valid for the character encoding, and even if it works without an exception then calling getBytes() on the String is not guaranteed to return the exact same bytes. 如果字节数组包含对字符编码无效的字节序列,则可能会引发异常,即使它没有异常也可以正常工作,但不能保证在String上调用getBytes()会返回完全相同的字节。

If you want to store a byte array in a database, store it as a BLOB (Binary Large OBject), or, if you really want to store it as a string, then convert it into text using for example Base64 encoding or as hexadecimal digits. 如果要在数据库中存储字节数组,请将其存储为BLOB(二进制大对象),或者,如果您确实要将其存储为字符串,则可以使用Base64编码或十六进制数字将其转换为文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM