本文介绍了将字节数组转换为String(Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Google App Engine中撰写网路应用程式。它允许人们在blobstore中基本编辑html代码,并存储为 .html 文件。

I'm writing a web application in Google app Engine. It allows people to basically edit html code that gets stored as an .html file in the blobstore.

m使用fetchData返回文件中所有字符的 byte [] 。我试图打印到一个html为了让用户编辑html代码。一切都很棒!

I'm using fetchData to return a byte[] of all the characters in the file. I'm trying to print to an html in order for the user to edit the html code. Everything works great!

这是我现在唯一的问题:

Here's my only problem now:

字节数组在转换时有一些问题到字符串。智能报价和几个字符出来看起来很时髦。 (?或日本符号等)具体来说,我看到有几个字节有负值导致的问题。

The byte array is having some issues when converting back to a string. Smart quotes and a couple of characters are coming out looking funky. (?'s or japanese symbols etc.) Specifically it's several bytes I'm seeing that have negative values which are causing the problem.

智能引号回来 -108 -109 。为什么是这样的,如何解码负字节以显示正确的字符编码?

The smart quotes are coming back as -108 and -109 in the byte array. Why is this and how can I decode the negative bytes to show the correct character encoding?

推荐答案

特殊编码(你应该知道)。将其转换为字符串的方法是:

The byte array contains characters in a special encoding (that you should know). The way to convert it to a String is:

String decoded = new String(bytes, "UTF-8");  // example for one encoding type

By The Way - 原始字节可能显示为负小数因为java数据类型 byte 已签名,它覆盖了从-128到127的范围。

By The Way - the raw bytes appear may appear as negative decimals just because the java datatype byte is signed, it covers the range from -128 to 127.

-109 = 0x93: Control Code "Set Transmit State"

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

The value (-109) is a non-printable control character in UNICODE. So UTF-8 is not the correct encoding for that character stream.

0x93 您要查找的智能引用,所以该编码的Java名称是Cp1252。下一行提供了一个测试代码:

0x93 in "Windows-1252" is the "smart quote" that you're looking for, so the Java name of that encoding is "Cp1252". The next line provides a test code:

System.out.println(new String(new byte[]{-109}, "Cp1252"));

这篇关于将字节数组转换为String(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 00:43
查看更多