【问题标题】:Java: Conversion between string and byte[] [duplicate]Java:字符串和字节[]之间的转换[重复]
【发布时间】:2012-12-09 09:19:19
【问题描述】:

可能重复:
Why does byteArray have a length of 22 instead of 20?

我只是想不通为什么我在这样转换时会出错

String mystring = "This is a String";
Log.v("string:", mystring);
Log.v("byte then string:", mystring.getBytes().toString()); 

输出如下

String: This is a string
byte then string: [B@44ecc390

谁能帮忙?我实际上只是想将一个字符串转换为字节,然后再转换为字符串。

【问题讨论】:

    标签: java android


    【解决方案1】:

    你应该使用

    Log.v("byte then string:", new String(mystring.getBytes()));

    【讨论】:

    • 不,你不应该 - 这将使用平台默认编码,这几乎是不合适的。
    • 假设使用的方法是byte[] bytes = String.getBytes(),则使用new String(bytes)一致,否则首先使用String.getBytes("UTF-8")
    • @JonSkeet 是的,这是真的,我正在举一个例子。将字节数组转换为字符串时,应始终指定编码。新字符串(字节数组,“UTF-8”)。
    • @aymeric:只有在使用相同编码的平台上获取字节时才一致。我个人总是会明确指定编码,即使它明确说“使用平台默认值”。这更清楚地表明了意图,IMO。
    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-02
    • 2012-11-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多