KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > openedit > store > Dom4JHelper


1 /*
2  * Created on Feb 15, 2005
3  */

4 package com.openedit.store;
5
6 import java.io.File JavaDoc;
7 import java.io.FileInputStream JavaDoc;
8 import java.io.FileOutputStream JavaDoc;
9 import java.io.IOException JavaDoc;
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 /**
22  * @author Matthew Avery, mavery@einnovation.com
23  * @deprecated use XMLUtils
24  */

25 public class Dom4JHelper
26 {
27
28     public void writeXmlFile( Element inRoot, File JavaDoc inFile ) throws IOException JavaDoc
29     {
30         // write to a temporary file first, in case there's an error
31
File JavaDoc tempFile = new File JavaDoc( inFile.getParentFile(), inFile.getName() + ".temp" );
32
33         inFile.getParentFile().mkdirs();
34         FileOutputStream JavaDoc fos = null;
35         try
36         {
37             fos = new FileOutputStream JavaDoc( 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 JavaDoc( "Unable to rename " + tempFile + " to " + inFile );
50         }
51     }
52
53     public Element getRootElement( File JavaDoc inFile, String JavaDoc inElementName ) throws IOException JavaDoc, DocumentException
54     {
55         if ( inFile.exists() )
56         {
57             SAXReader reader = new SAXReader();
58             Document document;
59             FileInputStream JavaDoc stream = null;
60             try
61             {
62                 stream = new FileInputStream JavaDoc(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