Java XML Document to File writeFile(String fileName, Document content)

Here you can find the source of writeFile(String fileName, Document content)

Description

write File

License

Apache License

Declaration

public static void writeFile(String fileName, Document content) throws IOException, TransformerException 

Method Source Code


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

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.xml.transform.OutputKeys;
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 {
    public static void writeFile(String fileName, Document content) throws IOException, TransformerException {
        writeFile(fileName, serializeDocument(content));
    }/*  ww  w .ja  v a  2  s  .  c om*/

    /**
     * write a String in a new file
     * 
     * @param fileName
     *            name of the new file
     * @param content
     *            content to write
     * @throws IOException
     */
    public static void writeFile(String fileName, String content) throws IOException {

        File file = new File(fileName);

        if (file.exists()) {
            throw new IOException("File " + fileName + " exist");
        }

        file.createNewFile();

        FileOutputStream flotS = new FileOutputStream(file);
        flotS.write(content.getBytes());
        flotS.close();
    }

    /**
     * serialize a Document in a XML UTF8 String
     * 
     * @param doc
     *            Dom Document to serialiaze
     * @return @throws IOException
     * @throws TransformerException
     */
    public static String serializeDocument(Document doc) throws IOException, TransformerException {
        ByteArrayOutputStream s = new ByteArrayOutputStream();

        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.setOutputProperty(OutputKeys.METHOD, "xml");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");

        DOMSource source = new DOMSource(doc);
        StreamResult outputTarget = new StreamResult(s);
        transformer.transform(source, outputTarget);

        return s.toString("UTF8");
    }
}

Related

  1. writeDomToFile(Document doc, String filename)
  2. writeDomToFile(Document dom, File outFile)
  3. writeDomToFile(Document dom, File outFile)
  4. writeDomToFile(Document dom, File outFile)
  5. writeDomToFile(String filename, Document document)
  6. writeTo(Document document, File output)
  7. writeToFile(Document doc, String file)
  8. writeToFile(Document doc, String filePath)
  9. writeToFile(File file, Document doc)