首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >将字节数组转换为字符串(Java)

将字节数组转换为字符串(Java)
EN

Stack Overflow用户
提问于 2011-04-15 14:17:43
回答 5查看 224.2K关注 0票数 85

我正在用Google app Engine编写一个web应用程序。它允许人们基本上编辑html代码,这些代码以.html文件的形式存储在blobstore中。

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

这是我现在唯一的问题:

字节数组在转换回字符串时有一些问题。聪明的引语和几个字符看起来很时髦。(?或日文符号等)具体地说,我看到有几个字节的值为负值,这是导致问题的原因。

在字节数组中,智能引号返回为-108-109。为什么会这样?我如何解码负字节以显示正确的字符编码?

EN

回答 5

Stack Overflow用户

发布于 2013-01-08 19:59:37

你可以试试这个。

代码语言:javascript
复制
String s = new String(bytearray);
票数 11
EN

Stack Overflow用户

发布于 2011-04-15 18:32:29

代码语言:javascript
复制
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();
    }
}

输出

代码语言:javascript
复制
65
65
A
票数 5
EN

Stack Overflow用户

发布于 2013-07-09 12:15:29

代码语言:javascript
复制
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
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/5673059

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档