English 中文(简体)
方法getBytes()返回未知字节
原标题:unknown bytes is returned by method getBytes()


import java.io.UnsupportedEncodingException;
import java.util.Arrays;

public class Main {
 public static void main(String[] args)
 {
  try 
  {
   String s = "s";
   System.out.println( Arrays.toString( s.getBytes("utf8") ) );
   System.out.println( Arrays.toString( s.getBytes("utf16") ) );
   System.out.println( Arrays.toString( s.getBytes("utf32") ) );
  }  
  catch (UnsupportedEncodingException e) 
  {
   e.printStackTrace();
  }
 }
}

控制台:


[115]
[-2, -1, 0, 115]
[0, 0, 0, 115]

它是什么?

[-2,-1]-???

此外,我指出,如果我这样做:


String s = new String(new char[]{ u1251 });
System.out.println( Arrays.toString( s.getBytes("utf8") ) );
System.out.println( Arrays.toString( s.getBytes("utf16") ) );
System.out.println( Arrays.toString( s.getBytes("utf32") ) );

控制台:


[-31, -119, -111]
[-2, -1, 18, 81]
[0, 0, 18, 81]
最佳回答

-2,-1是一个字节顺序标记(BOM-U+FEFF),表示以下文本以UTF-16格式编码。

你可能会得到这个,因为虽然只有一个UTF8和UTF32编码,但有两个UTF16编码UTF16LE和UTF16BE,其中16位值中的2个字节以Big Endian或Little Endian格式存储。

由于返回的值是0xFE-xFF,这表明编码是UTF16BE

问题回答

不要忘记在Java中字节是无符号的。所以-2,-1实际上意味着0xfe 0xff。。。并且U+FEFF是Unicode字节顺序标记(BOM)…这就是您在UTF-16版本中看到的。

为了避免在编码时获取BOM,请显式使用UTF-16BE或UTF-16LE。(我还建议使用由平台保证的名称,而不仅仅是“utf8”等。诚然,该名称保证可以不区分大小写地找到,但缺少连字符使其不太可靠,使用规范名称也没有缺点。)

神秘的-2,-1是一架UTF-16字节顺序标记(BOM)。其他负值只是字节。在Java中,字节类型是有符号的,范围从-128+127

java中的字节是一种有符号的类型,因此它具有负值是完全正常的。





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签