Java XML Document Save to File saveToFile(Document doc, File f, boolean indent)

Here you can find the source of saveToFile(Document doc, File f, boolean indent)

Description

save To File

License

Open Source License

Declaration

public static void saveToFile(Document doc, File f, boolean indent) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import org.w3c.dom.Document;

import org.w3c.dom.Node;

import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.Writer;
import java.io.OutputStreamWriter;
import java.io.BufferedWriter;

public class Main {
    public static void saveToFile(Document doc, File f, boolean indent) throws IOException {
        Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(f), "utf-8"));
        try {//from   ww w.j  a  va2s .  c om
            int n = indent ? 4 : 0;
            writeByDom(doc, writer, n);
        } finally {
            writer.close();
        }
    }

    private static void writeByDom(Node node, Writer writer, int indent) throws IOException {
        try {
            DOMImplementationRegistry registry = DOMImplementationRegistry.newInstance();
            DOMImplementationLS domImpLS = (DOMImplementationLS) registry.getDOMImplementation("LS 3.0");

            LSOutput output = domImpLS.createLSOutput();
            output.setCharacterStream(writer);
            output.setEncoding("utf-8");

            LSSerializer serializer = domImpLS.createLSSerializer();
            serializer.setNewLine("\n");
            if (indent > 0) {
                serializer.getDomConfig().setParameter("format-pretty-print", Boolean.TRUE);
            }
            serializer.write(node, output);
        } catch (ClassNotFoundException e) {
            throw new IllegalStateException(e);
        } catch (InstantiationException e) {
            throw new IllegalStateException(e);
        } catch (IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }
}

Related

  1. saveHumanReadable(Document document, File file)
  2. saveImpl(Document document, StreamResult output, Properties outputProperties)
  3. saveReportToFile(Node node, String documentFileName)
  4. saveTemporaryDocument(Document document, String folderName)
  5. saveToDisk(Document doc, OutputStream out)
  6. saveToFile(String filename, Document document)
  7. saveToXml(Document doc, OutputStream os)
  8. saveToXmlStr(Document doc)
  9. saveXML(Document doc, ByteArrayOutputStream outputStreamXML)