Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.xml.sax.SAXException;

public class Main {
    private static final ThreadLocal<DocumentBuilderFactory> documentBuilderFactory = new ThreadLocal<DocumentBuilderFactory>() {
        protected DocumentBuilderFactory initialValue() {
            return DocumentBuilderFactory.newInstance();
        };
    };

    /**
     * Read a file as an XML document.
     * @param file
     * @return the XML document
     */
    public static Document readXmlDocumentFromFile(File file) {
        try {
            InputStream inputStream = new FileInputStream(file);
            try {
                return readXmlDocumentFromStream(inputStream);
            } finally {
                inputStream.close();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * Read an input stream in as an XML document.
     * @param inputStream
     * @return the XML document
     */
    public static Document readXmlDocumentFromStream(InputStream inputStream) {
        try {
            DocumentBuilder documentBuilder = documentBuilderFactory.get().newDocumentBuilder();
            return documentBuilder.parse(inputStream);
        } catch (ParserConfigurationException e) {
            throw new RuntimeException(e);
        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}