private static Charset detect(InputStream input, Metadata metadata,
                                  EncodingDetector detector, LoadErrorHandler handler)
            throws IOException, TikaException {
        // Ask all given detectors for the character encoding
        try {
            Charset charset = detector.detect(input, metadata);
            if (charset != null) {
                return charset;
            }
        } catch (NoClassDefFoundError e) {
            // TIKA-1041: Detector dependencies not present.
            handler.handleLoadError(detector.getClass().getName(), e);
        }

        // Try determining the encoding based on hints in document metadata
        MediaType type = MediaType.parse(metadata.get(Metadata.CONTENT_TYPE));
        if (type != null) {
            String charset = type.getParameters().get("charset");
            if (charset != null) {
                try {
                    Charset cs = CharsetUtils.forName(charset);
                    metadata.set(TikaCoreProperties.DETECTED_ENCODING, cs.name());
                    metadata.set(TikaCoreProperties.ENCODING_DETECTOR,
                            "AutoDetectReader-charset-metadata-fallback");
                    return cs;
                } catch (IllegalArgumentException e) {
                    // ignore
                }
            }
        }

        throw new TikaException("Failed to detect the character encoding of a document");
    }
@param stream    stream from which to read -- make sure that it supports mark!
@param metadata
@param detector
@param handler
@throws IOException
@throws TikaException
tika-core/src/main/java/org/apache/tika/detect/AutoDetectReader.java