|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
再说第三点:我并没有提到服务器也要整合,然后是IDE,一个好的IDE能够200%提高开发的速度,就说图形方面:你是经过简单托拽和点击就能实现功能好那。xmlJava5中的Properties类如今可使用XML存取,经由过程loadFromXML和storeToXML办法完成。假定有上面这个属性表:windowSize:400,400windowLocation:456,300利用storeToXML后会失掉如许的XML文件<?xmlversion="1.0"encoding="UTF-8"?>
<!DOCTYPEpropertiesSYSTEM"http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Comment</comment>
<entrykey="windowLocation">400,400</entry>
<entrykey="windowSize">456,300</entry>
</properties>
可是假如要取得更具条理感的属性文件,可使用这里我写的一个Utility。它创建在一个读取和存储XML的类库上。这个类库收罗于ColumbaProject的util包,并有所修正。起首是XmlElement,用于暗示XML文件里的一个entry/*
*@(#)XmlElement.java
*Createdon2005-8-12
*/
packagecom.allenstudio.ir.util;importjava.util.Enumeration;
importjava.util.Hashtable;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Observable;
importjava.util.Vector;/**
*TheXmlElementisagenericcontainmentclassforelementswithinanXML
*file.
*<p>
*
*ItextendsObservablewhichshouldbeusedforguielementswhichare
*interestedinconfigurationchanges.
*<p>
*
*Showinterestedin:
*
*<pre>
*xmlElement.addObserver(yourObserver);
*</pre>
*
*<p>
*WhenmakingbiggerchangesonXmlElementandprobablyitssubnodesand/ora
*greaternumberofattributesatonce,youshouldjustchangeXmlElement
*directlyandmanuallynotifytheObserversbycalling:
*<p>
*
*<pre>
*xmlElement.setChanged();
*xmlElement.notifyObservers();
*</pre>
*
*<p>
*ThereagoodintroductionfortheObservable/Observerpatternin
*Model/View/Controllerbasedapplicationsatwww.javaworld.com:-
*{@linkhttp://www.javaworld.com/javaworld/jw-10-1996/jw-10-howto.html}
*
*@authorfdietz
*/
publicclassXmlElementextendsObservableimplementsCloneable{
Stringname;Stringdata;Hashtable<String,String>attributes;List<XmlElement>subElements;XmlElementparent;/**
*
*
*Constructor
*
*/
publicXmlElement(){
subElements=newVector<XmlElement>();
this.attributes=newHashtable<String,String>(10);
}/**
***
*
*Constructor
*
*@paramString
*Name
*
*/
publicXmlElement(Stringname){
this.name=name;
this.attributes=newHashtable<String,String>(10);
subElements=newVector<XmlElement>();
data="";
}/**
***
*
*Constructor
*
*@paramString
*Name
*@paramHashtable
*Attributes
*
*/
publicXmlElement(Stringname,Hashtable<String,String>attributes){
this.name=name;
this.attributes=attributes;
subElements=newVector<XmlElement>();
}/**
***
*
*Constructor
*
*@paramName
*String
*@paramData
*String
*
*/
publicXmlElement(Stringname,Stringdata){
this.name=name;
this.data=data;
subElements=newVector<XmlElement>();
this.attributes=newHashtable<String,String>(10);
}/**
*Addattributetothisxmlelement.
*
*@paramname
*nameofkey
*@paramvalue
*newattributevalue
*@returnoldattributevalue
*
*/
publicObjectaddAttribute(Stringname,Stringvalue){
if((value!=null)&&(name!=null)){
ObjectreturnValue=attributes.put(name,value);returnreturnValue;
}returnnull;
}/**
***
*
*@returnString
*@paramString
*Name
*
*/
publicStringgetAttribute(Stringname){
return((String)attributes.get(name));
}publicStringgetAttribute(Stringname,StringdefaultValue){
if(getAttribute(name)==null){
addAttribute(name,defaultValue);
}returngetAttribute(name);
}/**
***
*
*@returnString
*@paramString
*Name
*
*/
publicHashtable<String,String>getAttributes(){
returnattributes;
}/**
***
*
*
*@paramAttrs
*Hashtabletouseastheattributes
*
*/
publicvoidsetAttributes(Hashtable<String,String>attrs){
attributes=attrs;
}/**
***
*
*@returnEnumeration
*
*/
publicEnumerationgetAttributeNames(){
return(attributes.keys());
}/**
***
*
*@returnboolean
*@paramXmlElement
*E
*
*/
publicbooleanaddElement(XmlElemente){
e.setParent(this);return(subElements.add(e));
}publicXmlElementremoveElement(XmlElemente){
XmlElementchild=null;for(inti=0;i<subElements.size();i++){
child=(XmlElement)subElements.get(i);//FIXME--Thiswillmostlikelynotwork.
//Youwanttheelementremovedifthecontentsarethesame
//Notjustiftheelementreferenceisthesame.
if(child==e){
subElements.remove(i);
}
}return(child);
}publicXmlElementremoveElement(intindex){
return(XmlElement)subElements.remove(index);
}publicvoidremoveAllElements(){
subElements.clear();
}/**
*convieniencemethodfortheTreeView
*
*thismethodismodeledaftertheDefaultMutableTreeNode-class
*
*DefaultMutableTreeNodewrapsXmlElementforthispurpose
*
*/
publicvoidremoveFromParent(){
if(parent==null){
return;
}parent.removeElement(this);
parent=null;
}publicvoidappend(XmlElemente){
e.removeFromParent();addElement(e);
}/**
*
*convieniencemethodfortheTreeView
*
*@parame
*@paramindex
*/
publicvoidinsertElement(XmlElemente,intindex){
e.removeFromParent();subElements.add(index,e);
e.setParent(this);
}/**
***
*
*@returnVector
*
*/
publicListgetElements(){
returnsubElements;
}publicintcount(){
returnsubElements.size();
}/**
*Returnstheelementwhosehierachyisindicated
*by<code>path</code>.Thepathisseparatedwith
*periods(".").<br>
*<em>Note:ifonenodehasmorethanoneelements
*thathavethesamename,thatis,ifitssubnodes
*havethesamepath,onlythefirstoneisreturned.
*</em>
*@returnthefirstelementqualifiedwiththepath
*@parampaththepathstringofthespecifiedelement
*/
publicXmlElementgetElement(Stringpath){
inti=path.indexOf(.);
StringtopName;
StringsubName;if(i==0){
path=path.substring(1);
i=path.indexOf(.);
}if(i>0){
topName=path.substring(0,i);
subName=path.substring(i+1);
}else{
topName=path;
subName=null;
}intj;for(j=0;j<subElements.size();j++){
if(((XmlElement)subElements.get(j)).getName().equals(topName)){
if(subName!=null){
return(((XmlElement)subElements.get(j))
.getElement(subName));
}else{
return((XmlElement)subElements.get(j));
}
}
}returnnull;
}publicXmlElementgetElement(intindex){
return(XmlElement)subElements.get(index);
}/**
*Addsasubelementtothisone.Thepath
*isseparatedwithdots(".").
*
*@returnthe<code>XmlElement</code>added
*@parampathThesubpathofthesubelementtoadd
*
*/
publicXmlElementaddSubElement(Stringpath){
XmlElementparent=this;
XmlElementchild;
Stringname;while(path.indexOf(.)!=-1){
name=path.substring(0,path.indexOf(.));
path=path.substring(path.indexOf(.)+1);//ifpathstartsWith"/"->skip
if(name.length()==0)
continue;if(parent.getElement(name)!=null){
parent=parent.getElement(name);
}else{
child=newXmlElement(name);parent.addElement(child);
parent=child;
}}child=newXmlElement(path);
parent.addElement(child);returnchild;
}/**
*Addsasubelementtothisone
*
*@returnXmlElement
*@paramelement
*TheXmlElementtoadd
*
*/
publicXmlElementaddSubElement(XmlElemente){
e.setParent(this);
subElements.add(e);returne;
}/**
*Addsasubelementtothisone
*
*@returnXmlElement
*@paramName
*Thenameofthesubelementtoadd
*@paramData
*StringDataforthiselement
*/
publicXmlElementaddSubElement(Stringname,Stringdata){
XmlElemente=newXmlElement(name);
e.setData(data);
e.setParent(this);
subElements.add(e);returne;
}/**
*Setstheparentelement
*
*@paramParent
*TheXmlElementthatcontainsthisone
*
*/
publicvoidsetParent(XmlElementparent){
this.parent=parent;
}/**
*GivestheXmlElementcontainingthecurrentelement
*
*@returnXmlElement
*
*/
publicXmlElementgetParent(){
returnparent;
}/**
*Setsthedataforthiselement
*
*@paramD
*TheStringrepresentationofthedata
*
*/
publicvoidsetData(Stringd){
data=d;
}/**
*ReturnsthedataassociatedwiththecurrentXmlelement
*
*@returnString
*
*/
publicStringgetData(){
returndata;
}/**
*ReturnsthenameofthecurrentXmlelement
*
*@returnString
*
*/
publicStringgetName(){
returnname;
}/**
***
*
*@paramout
*OutputStreamtoprintthedatato
*
*//*
*publicvoidwrite(OutputStreamout)throwsIOException{PrintWriterPW=
*newPrintWriter(out);PW.println("<?xmlversion="1.0"
*encoding="UTF-8"?>");if(SubElements.size()>0){for(inti=0;i<
*SubElements.size();i++){((XmlElement)
*SubElements.get(i))._writeSubNode(PW,4);}}PW.flush();}
*//**
*Printssubnodestothegivendatastream
*
*@paramout
*PrintWritertouseforprinting
*@paramindent
*Numberofspacestoindentthings
*
*//*
*privatevoid_writeSubNode(PrintWriterout,intindent)throws
*IOException{_writeSpace(out,indent);out.print("<"+Name);//if(
*Attributes.size()>1)out.print("");
*
*for(Enumeratione=Attributes.keys();e.hasMoreElements();){StringK=
*(String)e.nextElement();out.print(K+"=""+Attributes.get(K)+""
*b");
*}out.print(">");
*
*if(Data!=null&&!Data.equals("")){if(Data.length()>20){
*out.println("");_writeSpace(out,indent+2);}out.print(Data);}if
*(SubElements.size()>0){out.println("");for(inti=0;i<
*SubElements.size();i++){((XmlElement)
*SubElements.get(i))._writeSubNode(out,indent+4);}_writeSpace(out,
*indent);}out.println("</"+Name+">");
*}
*//**
*Printsoutagivennumberofspaces
*
*@paramout
*PrintWritertouseforprinting
*@paramnumSpaces
*Numberofspacestoprint
*
*//*
*privatevoid_writeSpace(PrintWriterout,intnumSpaces)throws
*IOException{
*
*for(inti=0;i<numSpaces;i++)out.print("");}
*
*publicstaticvoidprintNode(XmlElementNode,Stringindent){String
*Data=Node.getData();if(Data==null||Data.equals("")){
*System.out.println(indent+Node.getName());}else{
*System.out.println(indent+Node.getName()+"="+Data+"");}
*VectorSubs=Node.getElements();inti,j;for(i=0;i<Subs.size();
*i++){printNode((XmlElement)Subs.get(i),indent+"");}}
*/
publicstaticvoidprintNode(XmlElementnode,Stringindent){
Stringdata=node.getData();if((data==null)||data.equals("")){
System.out.println(indent+node.getName());
}else{
System.out.println(indent+node.getName()+"="+data+"");
}//printattributes
for(Enumerationenumeration=node.getAttributes().keys();enumeration
.hasMoreElements();){
Stringkey=(String)enumeration.nextElement();
Stringvalue=node.getAttribute(key);
System.out.println(indent+key+":"+value);
}Listsubs=node.getElements();for(Iteratorit=subs.iterator();it.hasNext();){
printNode((XmlElement)it.next(),indent+"");//for(i=0;i<subs.size();i++){
//printNode((XmlElement)subs.get(i),indent+"");
}
}/**{@inheritDoc}*/
@SuppressWarnings("unchecked")
@Override
publicObjectclone(){
try{
XmlElementclone=(XmlElement)super.clone();//createsashallow
//copyofthis
//objectif(attributes!=null){
clone.setAttributes((Hashtable<String,String>)getAttributes().clone());
}if(subElements!=null){
clone.subElements=newVector();Listchilds=getElements();
XmlElementchild;for(Iteratorit=childs.iterator();it.hasNext();){
child=(XmlElement)it.next();//for(inti=0;i<childs.size();i++){
//child=(XmlElement)childs.get(i);
clone.addSubElement((XmlElement)child.clone());
}
}returnclone;
}catch(CloneNotSupportedExceptioncnse){
thrownewInternalError("CouldnotcloneXmlElement:"+cnse);
}
}/**
*Setsthename.
*
*@paramname
*Thenametoset
*/
publicvoidsetName(Stringname){
this.name=name;
}/**
*NotifyallObservers.
*
*@seejava.util.Observable#notifyObservers()
*/
@Override
publicvoidnotifyObservers(){
setChanged();
super.notifyObservers();
}/**
*Returnstrueifthespecifiedobjectsareequal.Theyareequalifthey
*arebothnullORifthe<code>equals()</code>methodreturntrue.(
*<code>obj1.equals(obj2)</code>).
*
*@paramobj1
*firstobjecttocomparewith.
*@paramobj2
*secondobjecttocomparewith.
*@returntrueiftheyrepresentthesameobject;falseifoneofthemis
*nullorthe<code>equals()</code>methodreturnsfalse.
*/
privatebooleanequals(Objectobj1,Objectobj2){
booleanequal=false;if((obj1==null)&&(obj2==null)){
equal=true;
}elseif((obj1!=null)&&(obj2!=null)){
equal=obj1.equals(obj2);
}returnequal;
}/**{@inheritDoc}
*Recursivecomparison.
*/
@Override
publicbooleanequals(Objectobj){
booleanequal=false;if((obj!=null)&&(objinstanceofXmlElement)){
XmlElementother=(XmlElement)obj;if(equals(attributes,other.attributes)
&&equals(data,other.data)&&equals(name,other.name)
&&equals(subElements,other.subElements)){
equal=true;
}
}returnequal;
}/**{@inheritDoc}*/
@Override
publicinthashCode(){
//Hashcodevalueshouldbebuffered.
inthashCode=23;if(attributes!=null){
hashCode+=(attributes.hashCode()*13);
}if(data!=null){
hashCode+=(data.hashCode()*17);
}if(name!=null){
hashCode+=(name.hashCode()*29);
}if(subElements!=null){
hashCode+=(subElements.hashCode()*57);
}returnhashCode;
}
}然后是XmlIO,用于读写。/*
*@(#)XmlIO.java
*Createdon2005-8-12
*/
packagecom.allenstudio.ir.util;importjava.io.BufferedWriter;
importjava.io.CharArrayWriter;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.io.OutputStreamWriter;
importjava.io.Writer;
importjava.net.URL;
importjava.util.Enumeration;
importjava.util.Iterator;
importjava.util.List;
importjava.util.Vector;
importjava.util.logging.Logger;importjavax.swing.JOptionPane;
importjavax.xml.parsers.SAXParser;
importjavax.xml.parsers.SAXParserFactory;importorg.xml.sax.Attributes;
importorg.xml.sax.SAXException;
importorg.xml.sax.XMLReader;
importorg.xml.sax.helpers.DefaultHandler;/**
*XMLIOreadingandwritingutility.
*
*@authorfdietz
*/
publicclassXmlIOextendsDefaultHandler{privatestaticfinalLoggerLOG=Logger.getLogger("org.columba.core.xml");privatestaticfinalStringROOT_XML_ELEMENT_NAME="__INSPIRENTO_XML_TREE_TOP__";//Listofsub-elements
@SuppressWarnings("unused")
privateList<XmlElement>elements;//Toplevelelement(Usedtoholdeverythingelse)
privateXmlElementrootElement;//Thecurrentelementyouareworkingon
privateXmlElementcurrentElement;//Forwritingoutthedata
//Indentforeachlevel
privateintwriteIndent=2;//Maximumdatatoputona"oneliner"
privateintmaxOneLineData=20;//TheSAX2parser...
@SuppressWarnings("unused")
privateXMLReaderxr;//Bufferforcollectingdatafrom
//the"characters"SAXevent.
privateCharArrayWritercontents=newCharArrayWriter();
privateURLurl=null;/*
//Defaultconstructor
publicXmlIO(){
}
*/
/*
//setupandloadconstructor
publicXmlIO(StringFilePath){
currentElement=null;
}
*/
publicXmlIO(URLurl){
super();
this.url=url;
}//setupandloadconstructor
publicXmlIO(){
currentElement=null;
}//setupandloadconstructor/**
*CreatesaXmlIOobjectwiththespecifiedelementatthetop.
*@paramelementtheelementatthetop.
*/
publicXmlIO(XmlElementelement){
rootElement=newXmlElement(ROOT_XML_ELEMENT_NAME);
rootElement.addElement(element);
}publicvoidsetURL(URLurl){
this.url=url;
}publicbooleanload(){
//this.file=F;
returnload(url);
}//Loadafile.Thisiswhatstartsthingsoff./**
*LoadsfromtheInputStreamintotherootXmlElement.
*@paraminputtheinputstreamtoloadfrom.
*/
publicbooleanload(InputStreaminput){
elements=newVector<XmlElement>();
rootElement=newXmlElement(ROOT_XML_ELEMENT_NAME);
currentElement=rootElement;try{
//CreatetheXMLreader...
//xr=XMLReaderFactory.createXMLReader();
SAXParserFactoryfactory=SAXParserFactory.newInstance();//SettheContentHandler...
//xr.setContentHandler(this);
SAXParsersaxParser=factory.newSAXParser();saxParser.parse(input,this);
}catch(javax.xml.parsers.ParserConfigurationExceptionex){
LOG.severe("XMLconfigerrorwhileattemptingtoreadfromtheinputstream
"+input+"");
LOG.severe(ex.toString());
ex.printStackTrace();return(false);
}catch(SAXExceptionex){
//Error
LOG.severe("XMLparseerrorwhileattemptingtoreadfromtheinputstream
"+input+"");
LOG.severe(ex.toString());
ex.printStackTrace();return(false);
}catch(IOExceptionex){
LOG.severe("I/Oerrorwhileattemptingtoreadfromtheinputstream
"+input+"");
LOG.severe(ex.toString());
ex.printStackTrace();return(false);
}//XmlElement.printNode(getRoot(),"");
return(true);
}/**
*Loadafile.Thisiswhatstartsthingsoff.
*@paraminputURLtheURLtoloadXMLfrom.
*/
publicbooleanload(URLinputURL){
elements=newVector<XmlElement>();
rootElement=newXmlElement(ROOT_XML_ELEMENT_NAME);
currentElement=rootElement;try{
//CreatetheXMLreader...
//xr=XMLReaderFactory.createXMLReader();
SAXParserFactoryfactory=SAXParserFactory.newInstance();//SettheContentHandler...
//xr.setContentHandler(this);
SAXParsersaxParser=factory.newSAXParser();saxParser.parse(inputURL.toString(),this);
}catch(javax.xml.parsers.ParserConfigurationExceptionex){
LOG.severe("XMLconfigerrorwhileattemptingtoreadXMLfile
"+inputURL+"");
LOG.severe(ex.toString());
ex.printStackTrace();return(false);
}catch(SAXExceptionex){
//Error
LOG.severe("XMLparseerrorwhileattemptingtoreadXMLfile
"+inputURL+"");
LOG.severe(ex.toString());
ex.printStackTrace();return(false);
}catch(IOExceptionex){
LOG.severe("I/OerrorwhileattemptingtoreadXMLfile
"+inputURL+"");
LOG.severe(ex.toString());
ex.printStackTrace();return(false);
}//XmlElement.printNode(getRoot(),"");
return(true);
}//Implementthecontenthandermethodsthat
//willdelegateSAXeventstothetagtrackernetwork.
@Override
publicvoidstartElement(StringnamespaceURI,StringlocalName,
StringqName,Attributesattrs)throwsSAXException{
//Resettingcontentsbuffer.
//Assumingthattagseithertagcontentorchildren,notboth.
//ThisisusuallythecasewithXMLthatisrepresenting
//datastrucuturesinaprogramminglanguageindependantway.
//ThisassumptionisnottypicallyvalidwhereXMLisbeing
//usedintheclassicaltextmarkupstylewheretagging
//isusedtostylecontentandseveralstylesmayoverlap
//atonce.
try{
contents.reset();Stringname=localName;//elementnameif(name.equals("")){
name=qName;//namespaceAware=false
}XmlElementp=currentElement;currentElement=currentElement.addSubElement(name);
currentElement.setParent(p);if(attrs!=null){
for(inti=0;i<attrs.getLength();i++){
StringaName=attrs.getLocalName(i);//Attrnameif(aName.equals("")){
aName=attrs.getQName(i);
}currentElement.addAttribute(aName,attrs.getValue(i));
}
}
}catch(java.lang.NullPointerExceptionex){
LOG.severe("Null!!!");
LOG.severe(ex.toString());
ex.printStackTrace();
}
}@Override
publicvoidendElement(StringnamespaceURI,StringlocalName,StringqName)
throwsSAXException{
currentElement.setData(contents.toString().trim());
contents.reset();currentElement=currentElement.getParent();
}@Override
publicvoidcharacters(char[]ch,intstart,intlength)
throwsSAXException{
//accumulatethecontentsintoabuffer.
contents.write(ch,start,length);
}/**
*ReturnstherootfortheXmlElementhiearchy.
*NotethatthisXmlElementwillalwayshavethename<code>__COLUMBA_XML_TREE_TOP__</code>.
*<p>
*Methodsthatwanttoretrieveelementsfromthisrootshoulduse
*the{@linkXmlElement#getElement(String)}inordertogetthewanted
*element.
*@returnaXmlElementifithasbeenloadedorinitializedwithit;nullotherwise.
*/
publicXmlElementgetRoot(){
return(rootElement);
}publicvoiderrorDialog(StringMsg){
JOptionPane.showMessageDialog(null,"Error:"+Msg);
}publicvoidwarningDialog(StringMsg){
JOptionPane.showMessageDialog(null,"Warning:"+Msg);
}publicvoidinfoDialog(StringMsg){
JOptionPane.showMessageDialog(null,"Info:"+Msg);
}publicvoidsave()throwsException{
write(newFileOutputStream(url.getPath()));
}//
//Writerinterface
//
publicvoidwrite(OutputStreamout)throwsIOException{
BufferedWriterPW=newBufferedWriter(newOutputStreamWriter(out,
"UTF-8"));
PW.write("<?xmlversion="1.0"encoding="UTF-8"?>
");if(rootElement.subElements.size()>0){
for(inti=0;i<rootElement.subElements.size();i++){
_writeSubNode(PW,(XmlElement)rootElement.subElements.get(i),0);
}
}PW.flush();
}privatevoid_writeSubNode(Writerout,XmlElementelement,intindent)
throwsIOException{
_writeSpace(out,indent);
out.write("<");
out.write(element.getName());for(Enumeratione=element.getAttributeNames();e.hasMoreElements();){
StringK=(String)e.nextElement();
out.write(""+K+"=""+InspirentoUtilities.escapeText(element.getAttribute(K))+""");
}out.write(">");Stringdata=element.getData();if((data!=null)&&!data.equals("")){
if(data.length()>maxOneLineData){
out.write("
");
_writeSpace(out,indent+writeIndent);
}out.write(InspirentoUtilities.escapeText(data));
}ListsubElements=element.getElements();if(subElements.size()>0){
out.write("
");for(Iteratorit=subElements.iterator();it.hasNext();){
_writeSubNode(out,(XmlElement)it.next(),indent+writeIndent);//for(inti=0;i<subElements.size();i++){
//_writeSubNode(
//out,
//(XmlElement)subElements.get(i),
//indent+writeIndent);
}_writeSpace(out,indent);
}if(data.length()>maxOneLineData){
out.write("
");
_writeSpace(out,indent);
}out.write("</"+InspirentoUtilities.escapeText(element.getName())+">
");
}privatevoid_writeSpace(Writerout,intnumSpaces)
throwsIOException{
for(inti=0;i<numSpaces;i++){
out.write("");
}
}
}上面是承继Properties的ConfigurationManager,个中的getProperty和setProperty办法已被Overridden。/*
*@(#)ConfigurationManager.java
*Createdon2005-8-10
*/
packagecom.allenstudio.ir.core;importjava.util.*;
importjava.io.*;importcom.allenstudio.ir.util.*;/**
*ManagestheconfigurationforInspirento.<br>
*ThismanagerusesXMLformattostoreinformation.
*Theconfigurationfileis,bydefault,savedinthe
*"config"directoryandnamed"config.xml".Clearly,
*thisclassshouldbeasingleton,soweuse
*{@link#getInstance()}togetaninstanceandcall
*otherinstancemethodstogetthesettingsneeded
*byInspirento,suchas"windowSize","windowLocation",
*andetc.<br>
*Theprogramfirsttriestogettheconfigurationfrom
*this<code>ConfigurationManager</code>.Ifitfailsto
*getanykey,itusesthedefaultsettingspresettedin
*theprotected<code>default</code>field.
*
*@authorAllenChue
*/
publicclassConfigurationManagerextendsProperties{
publicstaticfinalStringCONFIG_DIRECTORY="config";
publicstaticfinalStringCONFIG_FILE="config.xml";
publicstaticfinalStringCOMMON_PREFIX="Inspirento.";
privatestaticConfigurationManagerinstance=null;
privateXmlIOxmlIO;
/**
*Privateconstructorforsingletonuse.
*/
privateConfigurationManager(){
initDefaultSettings();
readIn();
}
publicstaticConfigurationManagergetInstance(){
if(instance!=null){
returninstance;
}else{
instance=newConfigurationManager();
returninstance;
}
}
publicvoidreadIn(){
try{
FileconfigFile=newFile(
CONFIG_DIRECTORY+
System.getProperty("file.separator")+
CONFIG_FILE);//$NON-NLS-1$
if(configFile.exists()){
FileInputStreamconfigStream=newFileInputStream(configFile);
xmlIO=newXmlIO();
xmlIO.load(configStream);
configStream.close();
}
}catch(Exceptione){
System.out.println("Cannotloadconfigurationfile"+
"supposedtobeat"configconfig.xml""+
"
Defaultsettingswillbestoredasthereplacement.");//$NON-NLS-1$
writeDefaultsToFile();
e.printStackTrace();
}
}
publicvoidwriteBack(){
try{
FileOutputStreamconfigFile=newFileOutputStream(
CONFIG_DIRECTORY+
System.getProperty("file.separator")+
CONFIG_FILE);
xmlIO.write(configFile);
configFile.close();
}catch(Exceptione){
System.out.println("Cannotwriteconfigurationfile"+
"to"configconfig.xml"");//$NON-NLS-1$
e.printStackTrace();
}
}
/**
*UsesXMLparsertogetthespecifiedproperty.
*Ifthereisnosuchakey,themethodreturns
*<code>null</code>.
*@paramkeythekeyoftheproperty
*@returnthepropertyvalue
*/
@Override
publicsynchronizedStringgetProperty(Stringkey){
Stringvalue=xmlIO.getRoot().getElement(Constants.PROJECT_NAME+
"."+getPath(key)[0]).getAttribute(getPath(key)[1]);
if(value==null){//Perhapssomeelementislostinthefile
value=defaults.getProperty(key);
setProperty(key,value);//nullvaluehasnosideeffect
newThread(){
@Override
publicvoidrun(){
writeBack();
}
}.start();
}
returnvalue;
}
@Override
publicsynchronizedObjectsetProperty(Stringkey,Stringvalue){
xmlIO.getRoot().getElement(Constants.PROJECT_NAME+
"."+getPath(key)[0]).addAttribute(getPath(key)[1],value);
returnvalue;
}
/**
*Whentheconfigurationfileislost,thismethod
*isusedtowritethedefaultsettingsstoredin
*theprogramitselftofile.
*
*/
privatevoidwriteDefaultsToFile(){
Enumerationkeys=defaults.keys();
XmlElementxe=newXmlElement(Constants.PROJECT_NAME);
xmlIO=newXmlIO(xe);
for(;keys.hasMoreElements();){
StringpathText=(String)keys.nextElement();String[]path=getPath(pathText);
//Testiftheelementtobemodifiedexists
XmlElementelementAdded=xe.getElement(path[0]);
if(elementAdded==null){
ele
还有就是总有人问我到底该学习什么语言,什么语言有前途,那么我的回答是不论是C,C++,java,.net,ruby,asp或是其他语言都可以学,编程的关键不是语言,而是思想。 |
|