How do I encode/decode UTF-16LE byte arrays with a BOM?

后端 未结 5 619
北荒
北荒 2020-12-09 08:52

I need to encode/decode UTF-16 byte arrays to and from java.lang.String. The byte arrays are given to me with a Byte Order Marker (BOM), and I need to encoded b

5条回答
  •  悲哀的现实
    2020-12-09 09:23

    This is an old question, but still, I couldn't find an acceptable answer for my situation. Basically, Java doesn't have a built-in encoder for UTF-16LE with a BOM. And so, you have to roll out your own implementation.

    Here's what I ended up with:

    private byte[] encodeUTF16LEWithBOM(final String s) {
        ByteBuffer content = Charset.forName("UTF-16LE").encode(s);
        byte[] bom = { (byte) 0xff, (byte) 0xfe };
        return ByteBuffer.allocate(content.capacity() + bom.length).put(bom).put(content).array();
    }
    

提交回复
热议问题