Java tutorial
//package com.java2s; /* * #%L * VisBio application for visualization of multidimensional biological * image data. * %% * Copyright (C) 2002 - 2014 Board of Regents of the University of * Wisconsin-Madison. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; public class Main { /** Writes the given DOM to the specified file on disk. */ public static void writeXML(final File file, final Document doc) { try { final FileOutputStream out = new FileOutputStream(file); writeXML(out, doc); out.close(); } catch (final IOException exc) { exc.printStackTrace(); } } /** * Writes the given DOM to a string. * * @return The string to which the DOM was written. */ public static String writeXML(final Document doc) { final ByteArrayOutputStream os = new ByteArrayOutputStream(); writeXML(os, doc); return os.toString(); } /** Writes the given DOM to the specified output stream. */ public static void writeXML(final OutputStream os, final Document doc) { try { final TransformerFactory transformFactory = TransformerFactory.newInstance(); final Transformer idTransform = transformFactory.newTransformer(); final Source input = new DOMSource(doc); final Result output = new StreamResult(os); idTransform.transform(input, output); } catch (final TransformerException exc) { exc.printStackTrace(); } // append newline to end of output try { os.write(System.getProperty("line.separator").getBytes()); } catch (final IOException exc) { exc.printStackTrace(); } } }