Here you can find the source of saveDocument(Document doc, File file)
public static void saveDocument(Document doc, File file) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.nio.charset.Charset; import java.nio.charset.CharsetEncoder; 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 javax.xml.transform.stream.StreamSource; import org.w3c.dom.Document; public class Main { public static void saveDocument(Document doc, File file) throws IOException { File parentDir = file.getParentFile(); if ((parentDir != null) && !parentDir.exists()) { parentDir.mkdirs();/* w w w . j av a 2s . c om*/ } writeDocument(doc, new FileOutputStream(file)); } public static void saveDocument(Document doc, File transform, File file) throws IOException { try { TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", new Integer(2)); Transformer transformer = tFactory.newTransformer(new StreamSource(transform)); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); FileOutputStream fos = new FileOutputStream(file.getPath()); DOMSource source = new DOMSource(doc); CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder(); StreamResult result = new StreamResult(new OutputStreamWriter(fos, utf8Encoder)); transformer.transform(source, result); fos.close(); } catch (TransformerException e) { throw new IOException(e); } } public static void writeDocument(Document doc, OutputStream os) throws IOException { try { TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2"); DOMSource source = new DOMSource(doc); CharsetEncoder utf8Encoder = Charset.forName("UTF-8").newEncoder(); StreamResult result = new StreamResult(new OutputStreamWriter(os, utf8Encoder)); transformer.transform(source, result); } catch (TransformerException e) { System.err.println(e.getMessage()); } } }