将字节数组转换为String(Java)

Jos*_*osh 85 java google-app-engine bytearray character-encoding

我正在Google App Engine中编写一个Web应用程序.它允许人们基本上编辑作为.html文件存储在blobstore中的html代码.

我正在使用fetchData来返回byte[]文件中的所有字符.我正在尝试打印到html,以便用户编辑html代码.一切都很棒!

这是我现在唯一的问题:

转换回字符串时,字节数组有一些问题.聪明的报价和几个角色看起来很时髦.(?或日语符号等)具体来说,我看到的几个字节都有负值导致问题.

智能引号赶回来,-108-109字节数组英寸 为什么这样,我如何解码负字节以显示正确的字符编码?

And*_*s_D 141

字节数组包含特殊编码的字符(您应该知道).将其转换为String的方法是:

String decoded = new String(bytes, "UTF-8");  // example for one encoding type
Run Code Online (Sandbox Code Playgroud)

按方式 - 原始字节出现可能显示为负小数,因为java数据类型byte已签名,它涵盖-128到127的范围.


-109 = 0x93: Control Code "Set Transmit State"
Run Code Online (Sandbox Code Playgroud)

值(-109)是UNICODE中的不可打印控制字符.因此UTF-8不是该字符流的正确编码.

0x93在"Windows-1252"中,您正在寻找"智能引用",因此该编码的Java名称为"Cp1252".下一行提供了一个测试代码:

System.out.println(new String(new byte[]{-109}, "Cp1252")); 
Run Code Online (Sandbox Code Playgroud)

  • 我尝试过使用UTF-8,它仍然是以?的形式出现的.为什么没有找到这些负值的映射? (5认同)

dav*_*wil 25

Java 7及以上版本

您还可以将所需的编码String作为StandardCharsets中Charset常量传递给构造函数.这可能比将编码作为a更安全,如其他答案中所建议的那样.String

例如,对于UTF-8编码

String bytesAsString = new String(bytes, StandardCharsets.UTF_8);
Run Code Online (Sandbox Code Playgroud)

  • @ james.garriss我不认为是这样,因为我只是提到Java 7中引入的新构造函数,允许将编码作为常量传递,在我看来,这比以前的api更好,更安全。前面的答案中提到过,如果有的话,编码是作为字符串传递的。 (2认同)

Muh*_*Ali 11

你可以试试这个.

String s = new String(bytearray);
Run Code Online (Sandbox Code Playgroud)

  • 你可以试试......但几乎在所有情况下它都会失败. (9认同)

Adi*_*ing 5

public class Main {

    /**
     * Example method for converting a byte to a String.
     */
    public void convertByteToString() {

        byte b = 65;

        //Using the static toString method of the Byte class
        System.out.println(Byte.toString(b));

        //Using simple concatenation with an empty String
        System.out.println(b + "");

        //Creating a byte array and passing it to the String constructor
        System.out.println(new String(new byte[] {b}));

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().convertByteToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

产量

65
65
A
Run Code Online (Sandbox Code Playgroud)


小智 5

public static String readFile(String fn)   throws IOException 
{
    File f = new File(fn);

    byte[] buffer = new byte[(int)f.length()];
    FileInputStream is = new FileInputStream(fn);
    is.read(buffer);
    is.close();

    return  new String(buffer, "UTF-8"); // use desired encoding
}
Run Code Online (Sandbox Code Playgroud)

  • 如果`read`抛出异常,此代码将泄漏资源. (3认同)