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)
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)
Muh*_*Ali 11
你可以试试这个.
String s = new String(bytearray);
Run Code Online (Sandbox Code Playgroud)
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)
| 归档时间: |
|
| 查看次数: |
221770 次 |
| 最近记录: |