private static String getEncodingName ( final InputStream is , final byte [ ] start , final int count ) { // '<' = 0x3c, '?' = 0x3f final int b0 = start [ 0 ] & 0xFF ; final int b1 = start [ 1 ] & 0xFF ; final int b2 = start [ 2 ] & 0xFF ; // check BOM if ( count > 1 ) { // UTF-16, big-endian if ( b0 == 0xFE && b1 == 0xFF ) return "UTF-16BE" ; // UTF-16, little-endian if ( b0 == 0xFF && b1 == 0xFE ) return "UTF-16LE" ; } if ( count >= 3 ) // UTF-8 with a BOM if ( b0 == 0xEF && b1 == 0xBB && b2 == 0xBF ) { try { is . skip ( 3 ) ; } catch ( final IOException ignore ) { } return "UTF-8" ; } if ( count == 4 ) { final byte [ ] [ ] arrays = { // UCS-4, big endian { ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x3C } , // UCS-4, little endian { ( byte ) 0x3C , ( byte ) 0x00 , ( byte ) 0x00 , ( byte ) 0x00 } , // UTF-16, big-endian { ( byte ) 0x00 , ( byte ) 0x3C , ( byte ) 0x00 , ( byte ) 0x3F } , // UTF-16, little-endian { ( byte ) 0x3C , ( byte ) 0x00 , ( byte ) 0x3F , ( byte ) 0x00 } , // EBCDIC, returns CP037 like xerces { ( byte ) 0x4C , ( byte ) 0x6F , ( byte ) 0xA7 , ( byte ) 0x94 } } ; final String [ ] encodings = { "ISO-10646-UCS-4" , "ISO-10646-UCS-4" , "UTF-16BE" , "UTF-16LE" , "CP037" } ; for ( int i = 0 ; i < encodings . length ; ++ i ) if ( Arrays . equals ( arrays [ i ] , start ) ) return encodings [ i ] ; } // default encoding return "UTF-8" ; }
the detection is done equally to the one in xerces parser