Here you can find the source of saveToFile(Document doc, File f, boolean indent)
public static void saveToFile(Document doc, File f, boolean indent) throws IOException
//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); } } }