移除UTF8编码文件或者文本中的BOM,移除utf8编码bom,在JAXB.unmars
分享于 点击 18496 次 点评:267
移除UTF8编码文件或者文本中的BOM,移除utf8编码bom,在JAXB.unmars
在JAXB.unmarshal或者JAXB.marshal时如果字符串中有utf8的bom头,将会导致一个腻歪的错误,我们不得不去一次一次改变文件的编码。
其实可以通过下面一小段代码检测文本或文件中是否包含utf8的bom,如果包含就把它移除掉,这样就没有后顾之忧了。
移除代码如下:
public class UTF8BOMFighter { private static final byte[] UTF8_BOM_BYTES = new byte[] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF }; private UTF8BOMFighter(){} static public String removeUTF8BOM(String xmlText) { byte[] bytes = xmlText.getBytes(); boolean containsBOM = bytes.length > 3 && bytes[0] == UTF8_BOM_BYTES[0] && bytes[1] == UTF8_BOM_BYTES[1] && bytes[2] == UTF8_BOM_BYTES[2]; if (containsBOM) { xmlText = new String(bytes, 3, bytes.length - 3); } return xmlText; } }
用户点评