简体   繁体   中英

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                 .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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM