1 4 package com.openedit.store; 5 6 import java.io.File ; 7 import java.io.FileInputStream ; 8 import java.io.FileOutputStream ; 9 import java.io.IOException ; 10 11 import org.dom4j.Document; 12 import org.dom4j.DocumentException; 13 import org.dom4j.DocumentHelper; 14 import org.dom4j.Element; 15 import org.dom4j.io.OutputFormat; 16 import org.dom4j.io.SAXReader; 17 import org.dom4j.io.XMLWriter; 18 19 import com.openedit.util.FileUtils; 20 21 25 public class Dom4JHelper 26 { 27 28 public void writeXmlFile( Element inRoot, File inFile ) throws IOException 29 { 30 File tempFile = new File ( inFile.getParentFile(), inFile.getName() + ".temp" ); 32 33 inFile.getParentFile().mkdirs(); 34 FileOutputStream fos = null; 35 try 36 { 37 fos = new FileOutputStream ( tempFile ); 38 XMLWriter writer = new XMLWriter( fos, OutputFormat.createPrettyPrint() ); 39 writer.write( inRoot ); 40 } 41 finally 42 { 43 FileUtils.safeClose( fos ); 44 } 45 46 inFile.delete(); 47 if ( !tempFile.renameTo(inFile) ) 48 { 49 throw new IOException ( "Unable to rename " + tempFile + " to " + inFile ); 50 } 51 } 52 53 public Element getRootElement( File inFile, String inElementName ) throws IOException , DocumentException 54 { 55 if ( inFile.exists() ) 56 { 57 SAXReader reader = new SAXReader(); 58 Document document; 59 FileInputStream stream = null; 60 try 61 { 62 stream = new FileInputStream (inFile); 63 document = reader.read(stream); 64 return document.getRootElement(); 65 } 66 finally 67 { 68 if ( stream != null ) 69 { 70 stream.close(); 71 } 72 } 73 } 74 else 75 { 76 return DocumentHelper.createElement( inElementName ); 77 } 78 } 79 80 } 81 | Popular Tags |