仓酷云

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 1114|回复: 18
打印 上一主题 下一主题

[学习教程] JAVA网页编程之一个自写的XML读写/存取属性的Java工具...

[复制链接]
飘灵儿 该用户已被删除
跳转到指定楼层
楼主
发表于 2015-1-18 11:36:41 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有帐号?立即注册

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或是其他语言都可以学,编程的关键不是语言,而是思想。
飘飘悠悠 该用户已被删除
沙发
发表于 2015-1-21 11:00:13 | 只看该作者
当然你也可以参加一些开源项目,一方面可以提高自己,另一方面也是为中国软件事业做贡献嘛!开发者在互联网上用CVS合作开发,用QQ,MSN,E-mail讨论联系,天南海北的程序员分散在各地却同时开发同一个软件,是不是很有意思呢?
小妖女 该用户已被删除
板凳
发表于 2015-1-31 07:46:23 | 只看该作者
你可以去承接一些项目做了,一开始可能有些困难,可是你有技术积累,又考虑周全,接下项目来可以迅速作完,相信大家以后都会来找你的,所以Money就哗啦啦的。。。。。。
因胸联盟 该用户已被删除
地板
发表于 2015-2-6 18:29:28 | 只看该作者
我大二,Java也只学了一年,觉得还是看thinking in java好,有能力的话看英文原版(中文版翻的不怎么好),还能提高英文文档阅读能力。
精灵巫婆 该用户已被删除
5#
发表于 2015-2-16 06:56:38 | 只看该作者
学Java必读的两个开源程序就是Jive和Pet Store.。 Jive是国外一个非常著名的BBS程序,完全开放源码。论坛的设计采用了很多先进的技术,如Cache、用户认证、Filter、XML等,而且论坛完全屏蔽了对数据库的访问,可以很轻易的在不同数据库中移植。论坛还有方便的安装和管理程序,这是我们平时编程时容易忽略的一部份(中国程序员一般只注重编程的技术含量,却完全不考虑用户的感受,这就是我们与国外软件的差距所在)。
爱飞 该用户已被删除
6#
发表于 2015-3-2 13:06:55 | 只看该作者
Java语言支持Internet应用的开发,在基本的Java应用编程接口中有一个网络应用编程接口(java net),它提供了用于网络应用编程的类库,包括URL、URLConnection、Socket、ServerSocket等。Java的RMI(远程方法激活)机制也是开发分布式应用的重要手段。
透明 该用户已被删除
7#
发表于 2015-3-11 03:47:09 | 只看该作者
当然你也可以参加一些开源项目,一方面可以提高自己,另一方面也是为中国软件事业做贡献嘛!开发者在互联网上用CVS合作开发,用QQ,MSN,E-mail讨论联系,天南海北的程序员分散在各地却同时开发同一个软件,是不是很有意思呢?
8#
发表于 2015-3-12 03:24:35 | 只看该作者
是一种简化的C++语言 是一种安全的语言,具有阻绝计算机病毒传输的功能
愤怒的大鸟 该用户已被删除
9#
发表于 2015-3-15 10:21:13 | 只看该作者
我大二,Java也只学了一年,觉得还是看thinking in java好,有能力的话看英文原版(中文版翻的不怎么好),还能提高英文文档阅读能力。
海妖 该用户已被删除
10#
发表于 2015-3-22 00:09:20 | 只看该作者
不过,每次的执行编译后的字节码需要消耗一定的时间,这同时也在一定程度上降低了 Java 程序的运行效率。
柔情似水 该用户已被删除
11#
发表于 2015-4-1 07:35:53 | 只看该作者
Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。
灵魂腐蚀 该用户已被删除
12#
发表于 2015-4-3 11:28:26 | 只看该作者
至于JDBC,就不用我多说了,你如果用java编过存取数据库的程序,就应该很熟悉。还有,如果你要用Java编发送电子邮件的程序,你就得看看Javamail 了。
山那边是海 该用户已被删除
13#
发表于 2015-4-6 08:42:44 | 只看该作者
一直感觉JAVA很大,很杂,找不到学习方向,前两天在网上找到了这篇文章,感觉不错,给没有方向的我指了一个方向,先不管对不对,做下来再说。
分手快乐 该用户已被删除
14#
发表于 2015-5-4 02:02:24 | 只看该作者
是一种使网页(Web Page)产生生动活泼画面的语言
不帅 该用户已被删除
15#
发表于 2015-5-8 15:45:06 | 只看该作者
Java 不同于一般的编译执行计算机语言和解释执行计算机语言。它首先将源代码编译成二进制字节码(bytecode),然后依赖各种不同平台上的虚拟机来解释执行字节码。从而实现了“一次编译、到处执行”的跨平台特性。
活着的死人 该用户已被删除
16#
发表于 2015-5-9 22:42:44 | 只看该作者
Java是一种计算机编程语言,拥有跨平台、面向对java
若天明 该用户已被删除
17#
发表于 2015-6-28 17:22:52 | 只看该作者
你现在最缺的是实际的工作经验,而不是书本上那些凭空想出来的程序。
简单生活 该用户已被删除
18#
发表于 2015-7-5 01:29:56 | 只看该作者
是一种为 Internet发展的计算机语言
深爱那片海 该用户已被删除
19#
发表于 2015-7-8 09:08:03 | 只看该作者
是一种将安全性(Security)列为第一优先考虑的语言
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|仓酷云 鄂ICP备14007578号-2

GMT+8, 2024-12-22 21:01

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表