Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Apache License 

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;

public class Main {
    /**
     * Determines if the given stream contains XML content. The stream will be
     * buffered and reset if necessary.
     * 
     * @param stream
     *            The InputStream to read.
     * @return true if the stream contains XML content; false otherwise.
     */
    public static boolean isXML(InputStream stream) {
        if (!stream.markSupported()) {
            stream = new BufferedInputStream(stream, 1024);
        }
        stream.mark(1024);
        byte[] bytes = new byte[1024];
        try {
            try {
                stream.read(bytes);
            } finally {
                stream.reset();
            }
        } catch (IOException iox) {
            throw new RuntimeException("Failed to read or reset stream. " + iox.getMessage());
        }
        try {
            XMLInputFactory factory = XMLInputFactory.newInstance();
            XMLStreamReader reader = factory.createXMLStreamReader(new ByteArrayInputStream(bytes));
            // If XML, now in START_DOCUMENT state; seek document element.
            reader.nextTag();
        } catch (XMLStreamException xse) {
            return false;
        }
        return true;
    }
}