1. Reading XML
Parsing XML using dom4j:http://sourceforge.net/projects/dom4j/files/
- Import org.dom4j.Document;
- Import org.dom4j.Element;
- Import Org.dom4j.io.SAXReader;
Try{File F=NewFile (filename); if(!f.exists ()) {System.out.println ("Error:config file doesn ' t exist!"); System.exit (1); } Saxreader Reader=NewSaxreader (); Document Doc; Doc=Reader.read (f); Element Root=doc.getrootelement (); Element data; Iterator<?> ITR = Root.elementiterator ("VALUE")); Data=(Element) itr.next (); Config.server= Data.elementtext ("Server"). Trim (); Config.user= Data.elementtext ("User"). Trim (); Config.pass= Data.elementtext ("Pass"). Trim (); Config.port= Data.elementtext ("Port"). Trim (); Config.dbname= Data.elementtext ("dbname"). Trim (); } Catch(Exception ex) {System.out.println ("Error:" +ex.tostring ()); }
Test XML
<?XML version= "1.0" encoding= "UTF-8"?> <CONFIG> <VALUE> <!--MySQL connection settings - <Server>127.0.0.1</Server> <dbname>Users</dbname> <User>Root</User> <Pass>Pass</Pass> <Port>3306</Port> </VALUE> </CONFIG>
2. Read properties
New Properties (); // ClassLoader ClassLoader = This.getclass (). getClassLoader (); // InputStream is = Classloader.getresourceasstream ("/healthfile.properties"); This . Getservletcontext (); = Context.getresourceasstream ("/web-inf/classes/healthfile.properties"); Prop.load (is); Is.close (); = Prop.getproperty ("Impl.class"); = Prop.getproperty ("Statichtml.local.rootPath");
Java read XML configuration file and properties configuration file