开发者

java: can I convert strings to byte arrays, without a BOM?

Suppose I have this code:

String encoding = "UTF-16";
String text = "[Hello StackOverflow]";
byte[] message= text.getBytes(encoding);

If I display the byte array in message, the result is:

0000    FE FF 00 5B 00 48 00 65 00 6C 00 6C 00 6F 00 20     ...[.H.e.l.l.o.
0010    00 53 00 74 00 61 00 63 00 6B 00 4F 00 76 00 65     .S.t.a.c.k.O.v.e
0020    00 72 00 66 00 6C 00 6F 00 77 00 5D            开发者_如何学JAVA     .r.f.l.o.w.]

As you can see, there's a BOM in the beginning.

How can I:

  1. generate a UTF-16 byte array that lacks a BOM, from a string?
  2. convert from a byte array that contains UTF-16 chars but lacks a BOM, back to a string?


You can explicitly choose a byte order by using "UTF-16BE" or "UTF-16LE" as the encoding. See the javadocs for Charset.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜