EncodingDetector extends DefaultHandler { public static String detect(InputStream in) throws IOException, ParserConfigurationException, SAXException { EncodingDetector detector = new EncodingDetector(); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http: SAXParser parser = factory.newSAXParser(); parser.parse(in, detector); return detector.encoding; } private  EncodingDetector(); static String detect(InputStream in); @Override void setDocumentLocator(Locator locator); @Override void startDocument();  }
@Test public void testXML() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<web-app></web-app>"; String encode = EncodingDetector.detect(new ByteArrayInputStream(xml.getBytes())); assertEquals("UTF-8", encode); xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>" + "<web-app></web-app>"; encode = EncodingDetector.detect(new ByteArrayInputStream(xml.getBytes())); assertEquals("UTF-8", encode); }
@Test public void testXMLWithWrongLocationDTD() throws Exception { String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<!DOCTYPE web-app PUBLIC \"- + "<web-app></web-app>"; try { String encode = EncodingDetector.detect(new ByteArrayInputStream(xml.getBytes())); assertEquals("UTF-8", encode); } catch (SAXParseException parseEx) { fail("Must not encounter exception here as we have disabled 'loading DTD' feature in SAXParser"); } }