private static char[] UTF32BE = { 0x0000, 0xFEFF };
private static char[] UTF32LE = { 0xFFFE, 0x0000 };
private static char[] UTF16BE = { 0xFEFF };
private static char[] UTF16LE = { 0xFFFE };
private static char[] UTF8 = { 0xEFBB, 0xBF };
private static boolean removeBOM(Reader reader, char[] bom) throws Exception {
int bomLength = bom.length;
reader.mark(bomLength);
char[] possibleBOM = new char[bomLength];
reader.read(possibleBOM);
for (int x = 0; x < bomLength; x++) {
if ((int) bom[x] != (int) possibleBOM[x]) {
reader.reset();
return false;
}
}
return true;
}
private static void removeBOM(Reader reader) throws Exception {
if (removeBOM(reader, UTF32BE)) {
return;
}
if (removeBOM(reader, UTF32LE)) {
return;
}
if (removeBOM(reader, UTF16BE)) {
return;
}
if (removeBOM(reader, UTF16LE)) {
return;
}
if (removeBOM(reader, UTF8)) {
return;
}
}
usage:
// xml can be read from a file, url or string through a stream
URL url = new URL("some xml url");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url.openStream()));
removeBOM(bufferedReader);