100字范文,内容丰富有趣,生活中的好帮手!
100字范文 > Java实现中文算数验证码(算数运算+-*/)

Java实现中文算数验证码(算数运算+-*/)

时间:2019-08-23 12:44:52

相关推荐

Java实现中文算数验证码(算数运算+-*/)

为了防止,页面向数据库暴力注册入力,用户登录暴力破解,所以加入验证码,验证码无法被软件获取上边的内容(加入算数计算,更加安全),所以在现在技术,暂时安全。

先看效果图:

第一次加载比较慢,防止无法加载验证码显示,后台获取准备好的默认正在加载图片(静态图片),后台图片获取好后,替代。

验证码效果图:

后台Java图片实现类VerificationCodeTool:

[java]view plain copy packagecom.tsXs.fileshare.tools; importjava.awt.Color; importjava.awt.Font; importjava.awt.Graphics; importjava.awt.Graphics2D; importjava.awt.image.BufferedImage; importjava.util.HashMap; importjava.util.Map; importjava.util.Random; importorg.apache.log4j.Logger; /** * *ClassName:VerificationCodeTool<br/> *Description:creatverificationcode<br/> *Date:-3-3下午08:37:55<br/> *<br/> * *@authoryptian@ * *firstmade *@version1.0.0<br/> * */ publicclassVerificationCodeTool{ //LOG privatestaticfinalLoggerLOG=Logger.getLogger(VerificationCodeTool.class); //verificationcodeimagewidth privatestaticfinalintIMG_WIDTH=146; //verificationcodeimageheight privatestaticfinalintIMG_HEIGHT=30; //Thenumberofinterferencelines privatestaticfinalintDISTURB_LINE_SIZE=15; //generatearandomnumber privateRandomrandom=newRandom(); //result privateintxyresult; //resultrandomstring privateStringrandomString; //ChineseNumbers //privatestaticfinalString[]CNUMBERS="零,一,二,三,四,五,六,七,八,九,十".split(","); //零一二三四五六七八九十乘除加减 //Here,mustbejavaUnicodecode privatestaticfinalStringCVCNUMBERS="\u96F6\u4E00\u4E8C\u4E09\u56DB\u4E94\u516D\u4E03\u516B\u4E5D\u5341\u4E58\u9664\u52A0\u51CF"; //Definitionofdrawingsinthecaptchacharactersfont,fontname,fontstyle,fontsize //staticfinalfont:InChinesecharactersgarbled privatefinalFontfont=newFont("黑体",Font.BOLD,18); //dataoperator privatestaticfinalMap<String,Integer>OPMap=newHashMap<String,Integer>(); static{ OPMap.put("*",11); OPMap.put("/",12); OPMap.put("+",13); OPMap.put("-",14); } /** *Thegenerationofimageverificationcode **/ publicBufferedImagedrawVerificationCodeImage(){ //image BufferedImageimage=newBufferedImage(IMG_WIDTH,IMG_HEIGHT,BufferedImage.TYPE_INT_RGB); //Inmemorytocreateabrush Graphicsg=image.getGraphics(); //Setthebrushcolor //g.setColor(getRandomColor(200,250)); g.setColor(Color.WHITE); //Fillthebackgroundcolor,usingthecurrentbrushcolourchangingbackgroundcolorimages //Themeaningofthefourparametersrespectively,startingxcoordinates,startingy,width,height. //imagebackground g.fillRect(0,0,IMG_WIDTH,IMG_HEIGHT); //Setthebrushcolor g.setColor(getRandomColor(200,250)); //imageborder g.drawRect(0,0,IMG_WIDTH-2,IMG_HEIGHT-2); //Setdisturblinecolor g.setColor(getRandomColor(110,133)); //Generaterandominterferencelines for(inti=0;i<DISTURB_LINE_SIZE;i++){ drawDisturbLine1(g); drawDisturbLine2(g); } //Generatearandomnumber,setreturndata getRandomMathString(); LOG.info("验证码:"+randomString); LOG.info("验证码结果:"+xyresult); //Thegeneratedrandomstringusedtosavethesystem StringBufferlogsu=newStringBuffer(); for(intj=0,k=randomString.length();j<k;j++){ intchid=0; if(j==1){ chid=OPMap.get(String.valueOf(randomString.charAt(j))); }else{ chid=Integer.parseInt(String.valueOf(randomString.charAt(j))); } Stringch=String.valueOf(CVCNUMBERS.charAt(chid)); logsu.append(ch); drawRandomString((Graphics2D)g,ch,j); } //=? drawRandomString((Graphics2D)g,"\u7B49\u4E8E\uFF1F",3); logsu.append("\u7B49\u4E8E\uFF1F"); LOG.info("汉字验证码:"+logsu); randomString=logsu.toString(); //Releasethebrushobject g.dispose(); returnimage; } /** *Getarandomstring **/ privatevoidgetRandomMathString(){ //Randomlygeneratednumber0to10 intxx=random.nextInt(10); intyy=random.nextInt(10); //savegetRandomString StringBuildersuChinese=newStringBuilder(); //random0,1,2 intRandomoperands=(int)Math.round(Math.random()*2); //multiplication if(Randomoperands==0){ this.xyresult=yy*xx; //suChinese.append(CNUMBERS[yy]); suChinese.append(yy); suChinese.append("*"); suChinese.append(xx); //division,divisorcannotbezero,Bedivisible }elseif(Randomoperands==1){ if(!(xx==0)&&yy%xx==0){ this.xyresult=yy/xx; suChinese.append(yy); suChinese.append("/"); suChinese.append(xx); }else{ this.xyresult=yy+xx; suChinese.append(yy); suChinese.append("+"); suChinese.append(xx); } //subtraction }elseif(Randomoperands==2){ this.xyresult=yy-xx; suChinese.append(yy); suChinese.append("-"); suChinese.append(xx); //add }else{ this.xyresult=yy+xx; suChinese.append(yy); suChinese.append("+"); suChinese.append(xx); } this.randomString=suChinese.toString(); } /** *Drawarandomstring *@paramgGraphics *@paramrandomStringrandomstring *@paramitherandomnumberofcharacters **/ publicvoiddrawRandomString(Graphics2Dg,Stringrandomvcch,inti){ //Setthestringfontstyle g.setFont(font); //Setthecolorstring intrc=random.nextInt(255); intgc=random.nextInt(255); intbc=random.nextInt(255); g.setColor(newColor(rc,gc,bc)); //randomstring //Setpictureinthepictureofthetextonthex,ycoordinates,randomoffsetvalue intx=random.nextInt(3); inty=random.nextInt(2); g.translate(x,y); //Setthefontrotationangle intdegree=newRandom().nextInt()%15; //Positivepointofview g.rotate(degree*Math.PI/180,5+i*25,20); //Characterspacingissetto15px //Usingthegraphicscontextofthecurrentfontandcolorrenderingbythespecifiedstringforagiventext. //Themostontheleftsideofthebaselineofthecharactersinthecoordinatesystemofthegraphicscontext(x,y)location //str-todrawstring.x-xcoordinate.y-ycoordinate. g.drawString(randomvcch,5+i*25,20); //ReverseAngle g.rotate(-degree*Math.PI/180,5+i*25,20); } /** *Drawlineinterference *@paramgGraphics **/ publicvoiddrawDisturbLine1(Graphicsg){ intx1=random.nextInt(IMG_WIDTH); inty1=random.nextInt(IMG_HEIGHT); intx2=random.nextInt(13); inty2=random.nextInt(15); //x1-Thefirstpointofthexcoordinate. //y1-Thefirstpointoftheycoordinate //x2-Thesecondpointofthexcoordinate. //y2-Thesecondpointoftheycoordinate. //X1andx2isthestartingpointcoordinates,x2andy2isendcoordinates. g.drawLine(x1,y1,x1+x2,y1+y2); } /** *Drawlineinterference *@paramgGraphics **/ publicvoiddrawDisturbLine2(Graphicsg){ intx1=random.nextInt(IMG_WIDTH); inty1=random.nextInt(IMG_HEIGHT); intx2=random.nextInt(13); inty2=random.nextInt(15); //x1-Thefirstpointofthexcoordinate. //y1-Thefirstpointoftheycoordinate //x2-Thesecondpointofthexcoordinate. //y2-Thesecondpointoftheycoordinate. //X1andx2isthestartingpointcoordinates,x2andy2isendcoordinates. g.drawLine(x1,y1,x1-x2,y1-y2); } /** *Forrandomcolor *@paramfcfc *@parambcbc *@returncolorrandomcolor **/ publicColorgetRandomColor(intfc,intbc){ if(fc>255){ fc=255; } if(bc>255){ bc=255; } //GeneraterandomRGBtrichromatic intr=fc+random.nextInt(bc-fc-16); intg=fc+random.nextInt(bc-fc-14); intb=fc+random.nextInt(bc-fc-18); returnnewColor(r,g,b); } /** *xyresult.<br/> * *@returnthexyresult<br/> * */ publicintgetXyresult(){ returnxyresult; } /** *randomString.<br/> * *@returntherandomString<br/> * */ publicStringgetRandomString(){ returnrandomString; } } 生产静态验证码(为了防止,加载慢,空白显示):[java]view plain copy packagecom.tsXs.fileshare.tools; importjava.awt.Color; importjava.awt.Graphics; importjava.awt.Graphics2D; importjava.awt.image.BufferedImage; importjava.io.BufferedOutputStream; importjava.io.File; importjava.io.FileOutputStream; importjavax.imageio.ImageIO; importjavax.swing.ImageIcon; importjavax.swing.filechooser.FileSystemView; importorg.apache.log4j.Logger; importcom.tsXs.fileshare.configuration.properties.StaticConstants; /** *ClassName:ImageTool<br/> *Description:getBufferedImagecreatimage<br/> *Date:-3-10下午05:05:38<br/> *<br/> * *@authoryptian@ * *firstmade *@version1.0.0<br/> * */ publicclassImageTool{ //LOG privatestaticfinalLoggerLOG=Logger.getLogger(ImageTool.class); //image privateBufferedImageimage; /** *createImage:outdestpathforimage *@paramfileLocationdestpath */ privatevoidcreateImage(StringfileLocation){ try{ FileOutputStreamfos=newFileOutputStream(fileLocation); BufferedOutputStreambos=newBufferedOutputStream(fos); ImageIO.write(image,"png",bos); //com.sun.image.codec.jpeg.JPEGImageEncoderencoder=com.sun.image.codec.jpeg.JPEGCodec.createJPEGEncoder(bos); //encoder.encode(image); bos.flush(); bos.close(); LOG.info("@2"+fileLocation+"图片生成输出成功"); }catch(Exceptione){ LOG.info("@2"+fileLocation+"图片生成输出失败",e); } } /** *createFileIconImage:createsharefilelisticon *@paramdestOutPathcreatefileiconsavedictory */ publicvoidcreateFileIconImage(StringdestOutPath){ //getpropertiesoperatetool PropertiesToolpropertiesTool=PropertiesTool.getInstance(StaticConstants.SHARE_FILE_CONFGURATION_PROPERTIES_PATH); //getsharefilerootpath StringshareFileRootPath=propertiesTool.getPropertiesValue("FileShareRootPath"); //rootdictory FilerootDictory=newFile(shareFileRootPath); //childfilelist File[]fileList=rootDictory.listFiles(); //childlistfiles Filefile=null; if(fileList!=null&&fileList.length>0){ LOG.info("分享文件根目录下文件数:"+fileList.length); for(inti=0,j=fileList.length;i<j;i++){ StringfileName=fileList[i].getName(); StringfileAllName=shareFileRootPath+fileName; file=newFile(fileAllName); //getfilesystemicon ImageIconfileIcon=(ImageIcon)FileSystemView.getFileSystemView().getSystemIcon(file); image=(BufferedImage)fileIcon.getImage(); if(image!=null){ LOG.info("@1"+fileName+"文件的图标获取成功"); } Graphicsg=image.getGraphics(); g.drawImage(image,0,0,null); StringfileNameX=fileName.substring(0,fileName.lastIndexOf(".")); //outimagetodest createImage(destOutPath+"\\"+fileNameX+".png"); LOG.info("@3"+fileName+"文件的图标生成成功"); } } } /** *creatDefaultVerificationCode:createdefaultverificationcode *@paramdestOutPathcreatecreatDefaultVerificationCodesavedictory */ publicvoidcreatDefaultVerificationCode(StringdestOutPath){ //verificationcodeimageheight //commenttocom.tss.fileshare.tools.VerificationCodeTool65row,please intimgwidth=146; intimgheight=30; intdisturblinesize=15; VerificationCodeToolvcTool=newVerificationCodeTool(); //defaultverificationcode image=newBufferedImage(imgwidth,imgheight,BufferedImage.TYPE_INT_RGB); Graphicsg=image.getGraphics(); g.setColor(Color.WHITE); g.fillRect(0,0,146,30); g.setColor(vcTool.getRandomColor(200,250)); g.drawRect(0,0,imgwidth-2,imgheight-2); for(inti=0;i<disturblinesize;i++){ vcTool.drawDisturbLine1(g); vcTool.drawDisturbLine2(g); } //玩命加载中… StringdefaultVCString="\u73A9\u547D\u52A0\u8F7D\u4E2D\u2026"; Stringdfch=null; for(inti=0;i<6;i++){ dfch=String.valueOf(defaultVCString.charAt(i)); vcTool.drawRandomString((Graphics2D)g,dfch,i); } LOG.info("默然验证码生成成功"); //Graphicsgvc=imagevc.getGraphics(); createImage(destOutPath+"\\defaultverificationcode.jpeg"); } /** *graphicsGeneration:createimage *@paramimgurldisplaypictureurl.eg:F:/imagetool/7.jpg<br/> *@paramimageOutPathNameimageoutpath+naem.eg:F:\\imagetool\\drawimage.jpg<br/> *@paramvariableParmeterLength;int,thirdparameterlength.<br/> *@paramdrawStringvariableParmeterLength;String[].<br/> */ publicvoidgraphicsGeneration(Stringimgurl,StringimageOutPathName,intvariableParmeterLength,String...drawString){ //Thewidthofthepicture intimageWidth=500; //Theheightofthepicture intimageHeight=400; image=newBufferedImage(imageWidth,imageHeight,BufferedImage.TYPE_INT_RGB); Graphicsgraphics=image.getGraphics(); graphics.setColor(Color.WHITE); //drawingimage graphics.fillRect(0,0,imageWidth,imageHeight); graphics.setColor(Color.BLACK); //drawstringstring,leftmargin,topmargin for(inti=0,j=variableParmeterLength;i<j;i++){ graphics.drawString(drawString[i],50,10+15*i); } //drawimageurl ImageIconimageIcon=newImageIcon(imgurl); //drawimage,leftmargin,topmargin //Thecoordinatesofthetopleftcornerasthecenter(x,y)[lefttopangle] //Imageobserver:Ifimgisnull,thismethoddoesnotperformanyaction graphics.drawImage(imageIcon.getImage(),200,0,null); createImage(imageOutPathName); } publicBufferedImagegetImage(){ returnimage; } publicvoidsetImage(BufferedImageimage){ this.image=image; } } 服务器,启动的时候,调用一次,生成默认图片到服务器“/servertempdictory/fileicon/”目录下:[java]view plain copy //createdefaultverificationcode StringfileIconDictory=serverPath+"\\servertempdictory\\fileicon"; imageTool.creatDefaultVerificationCode(fileIconDictory); 生成动态验证码,并保存值到session中(此处有登录和注册的分路,这个读者可忽略,走一条既可):[java]view plain copy /** *creatverificationcode **/ publicvoidverificationcode(){ //response HttpServletResponseresponse=ServletActionContext.getResponse(); //request HttpServletRequestrequest=ServletActionContext.getRequest(); //verificationcodedemander StringvCdemander=request.getParameter("vcdemander"); try{ //setencoding request.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=utf-8"); //Verificationcodetool VerificationCodeToolvcTool=newVerificationCodeTool(); BufferedImageimage=vcTool.drawVerificationCodeImage(); //Verificationcoderesult intvcResult=vcTool.getXyresult(); StringvcValue=vcTool.getRandomString(); //Setbancache //Cache-control:Specifytherequestandresponsefollowingcachingmechanism //no-cache:Indicatesarequestorresponsemessagecannotcache response.setHeader("Cache-Control","no-cache"); //Entityheaderfieldresponseexpirationdateandtimearegiven response.setHeader("Pragma","No-cache"); response.setDateHeader("Expires",0); //Settheoutputstreamcontentformatasimageformat response.setContentType("image/jpeg"); //session //true:ifthesessionexists,itreturnsthesession,orcreateanewsession. //false:ifthesessionexists,itreturnsthesession,otherwiseitreturnsnull. HttpSessionsession=request.getSession(true); //setverificationcodetosession //login if("userlogin".equals(vCdemander)){ session.setAttribute("verificationcodeuserlogin",vcResult); } //regiser if("userregister".equals(vCdemander)){ session.setAttribute("verificationcodeuserregister",vcResult); } //Totheoutputstreamoutputimage ImageIO.write(image,"JPEG",response.getOutputStream()); LOG.info("获取验证码成功:\n验证码:"+vcValue+"\n验证码结果:"+vcResult); }catch(Exceptione){ LOG.error("获取验证码失败",e); } } 用struts2实现,所以配置文件struts.xml:[sql]view plain copy <!--Setwhethertosupportdynamicmethodcalls,truetosupport,falsedoesnotsupport.--> <constantname="struts.enable.DynamicMethodInvocation"value="true"/> <!--Thesuffixspecifiedrequest--> <constantname="struts.action.extension"value="do,go,tsXs,action"></constant> <!--useroperation[firstloginserver,serverinitialize]--> <packagename="user"namespace="/fileshare"extends="struts-default"> <!--useroperate;Thewildcardmethodcall--> <actionname="user*"class="com.tsXs.fileshare.controller.UserController"method="{1}"> <resultname="success">/view/common/message.jsp</result> <resultname="error">/view/userLogin.jsp</result> </action> </package>

页面jsp显示代码:[java]view plain copy <tr> <tdwidth="100"> <spanclass="hint">*[验证码]:只能输入数字和负号"-"</span> </td> </tr> <tr> <tdwidth="100"> <labelfor="userRegPassWord">验证码</label> <inputtype="text"id="verificationcodereg"name="verificationcodereg"tabindex="3"maxlength="3"class="t_input"value=""style="ime-mode:disabled;"οnblur="checkuserverificationcode(this);"οnkeypress="return(/[\d-]/.test(String.fromCharCode(event.keyCode)));"/> <spanid="usvcmsg"></span> <inputtype="hidden"id="verificationcoderegflag"value=""/> </td> </tr> <tr> <tdwidth="140"> <divid="refreshvc"> <spanοnclick="refreshvc();"style="padding-left:49px;cursor:pointer;"><imgid="verificationcodeimg"src="${pageContext.request.contextPath}/servertempdictory/fileicon/defaultverificationcode.jpeg"/> <spanstyle="height:30px;width:16px;padding-left:4px;"><imgsrc="image/refreshvc.png"/></span> <spanstyle="font-size:12px;color:#2c629e;width:20px;">换一张</span> </span> </div> </td> </tr>

在js中用正则,保证只能输入,最多3位,可以在数字前输入一个"-",即onkeypress保证只能输入数字和"-":

[java]view plain copy varuserverificationcoderegex=/^(-{0,1}\d+){1,3}$/; if(userverificationcoderegex.test(userverificationcode)){..... jsp图片效果:

js动态刷新验证码:

[sql]view plain copy $(document).ready(function(){ //loadverificatinocode refreshvc(); }); //refreshverificationcode functionrefreshvc(){ varpath=$("#contextPath").val(); varrefreshvcurl=path+"/fileshare/userverificationcode.tsXs?vcdemander=userregister&time="+newDate(); $("#verificationcodeimg").attr("src",refreshvcurl); } 验证码验证:[java]view plain copy /** *checkverificationcode:checkverificationcodeequals */ ublicvoidcheckverificationcode(){ //request HttpServletRequestrequest=ServletActionContext.getRequest(); //response HttpServletResponseresponse=ServletActionContext.getResponse(); //outputstream PrintWriterout=null; //session HttpSessionsession=request.getSession(); //verificationcodefromclient Stringvcclient=null; //verificationcodefromserver Stringvcserver=null; //verificationcodedemander StringvCdemander=request.getParameter("vcdemander"); //checkverificationcodetoclienflag Stringchecktoclienflag=null; try{ //getverificationcodetosession //login if("userlogin".equals(vCdemander)){ vcclient=request.getParameter("vclogincode"); vcserver=String.valueOf(session.getAttribute("verificationcodeuserlogin")); } //regiser if("userregister".equals(vCdemander)){ vcclient=request.getParameter("vcregcode"); vcserver=String.valueOf(session.getAttribute("verificationcodeuserregister")); } vcclient=UserController.encodingconvert(vcclient); vcclient=vcclient==null?"":vcclient; if(vcclient.equals(vcserver)){ checktoclienflag="vcok"; }else{ checktoclienflag="vcwrong"; } //setnocache,contenttype,encoding response.setHeader("Cache-Control","no-cache"); response.setContentType("text/html"); response.setCharacterEncoding("GBK"); //outputstream out=response.getWriter(); out.print(checktoclienflag); LOG.info("验证码:vcclient:"+vcclient+"vcserver:"+vcserver+"验证顺利"); }catch(Exceptione){ LOG.error("vcclient:"+vcclient+"vcserver:"+vcserver+"验证失败",e); }finally{ out.flush(); out.close(); }[java]view plain copy properties辅助类:[java]view plain copy <preclass="java"name="code">/** *Copyright(c),TravelSky. *AllRightsReserved. *TravelSkyCONFIDENTIAL * *ProjectName:filesharetss *PackageName:com.tss.fileshare.controller.tools *FileName:PropertiesFileOperation.java *Date:-2-27下午05:30:05 * */ packagecom.tsXs.fileshare.tools; importjava.io.FileInputStream; importjava.io.FileNotFoundException; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; importjava.io.OutputStream; importjava.util.Enumeration; importjava.util.Properties; importorg.apache.log4j.Logger; /** * *ClassName:PropertiesFileOperationTool<br/> *Description:innerclassPropertiesfileoperation<br/> *Date:-2-27下午05:10:52<br/> *<br/> * *@authoryptian@ * *firstmade *@version1.0.0<br/> * */ publicclassPropertiesTool{ //LOG privatestaticfinalLoggerLOG=Logger.getLogger(PropertiesTool.class); //Singletoninstance privatestaticPropertiesToolinstance=newPropertiesTool(); privatestaticPropertiesproperties; /** * *CreatesanewSingletoninstanceofPropertiesFileOperation.<br/> */ privatePropertiesTool(){ } /** *getInstance:getpropertiesobject *@parampropertiesFilePathNamepropertiesfilepathandname *@return */ publicstaticPropertiesToolgetInstance(StringpropertiesFilePathName){ properties=loadPropertiesFile(propertiesFilePathName); returninstance; } /** * *loadPropertiesFile:Loadpropertiesfilebypathandname<br/> *@parampropertiesFilePathNamepathandnameofpropertiesfile<br/> *@returnpropertiesproperties */ privatestaticPropertiesloadPropertiesFile(StringpropertiesFilePathName){ Propertiesproperties=newProperties(); InputStreamisLoad=PropertiesTool.class.getClassLoader().getResourceAsStream(propertiesFilePathName); try{ //loaderproperties properties.load(isLoad); }catch(IOExceptione){ LOG.error(propertiesFilePathName+"propertiesfilereadfailure",e); }finally{ try{ isLoad.close(); }catch(IOExceptione){ LOG.error("propertiesfilestreamcloseerror",e); } } returnproperties; } /** ** *getPropertiesValue:Getpropertiesvaluebykey<br/> *@paramkeypropertieskey<br/> *@returnvaluepropertiesvalue */ publicStringgetPropertiesValue(Stringkey){ returnproperties.getProperty(key); } publicstaticStringgetInstanceByServerRealPathOfValue(StringpropertiesFileServerRealPathName,Stringkey){ StringpValue=null; try{ InputStreamisrLoad=newFileInputStream(propertiesFileServerRealPathName); properties.load(isrLoad); isrLoad.close(); pValue=properties.getProperty(key); }catch(IOExceptione){ LOG.error("Failedtogetthevalueundertheserverofthepropertiesfile",e); } returnpValue; } /** * *getProperties:Getpropertiesbykeyandvalue<br/> *@paramkeypropertieskey<br/> *@paramvaluepropertiesvalue */ publicvoidsetProperties(StringfilePath,Stringkey,Stringvalue){ try{ InputStreamis=newFileInputStream(filePath); OutputStreamos=newFileOutputStream(filePath); properties.load(is); properties.setProperty(key,value); properties.store(os,null); os.flush(); is.close(); os.close(); }catch(IOExceptione){ LOG.error("propertiesfilestreamcloseerror",e); } } /** * *alterProperties:alterpropertiesbykeyandvalue<br/> *@paramkeypropertieskey<br/> *@paramvaluepropertiesvalue */ publicvoidalterProperties(StringfilePath,Stringkey,Stringvalue){ try{ InputStreamis=newFileInputStream(filePath); OutputStreamos=newFileOutputStream(filePath); properties.load(is); properties.remove(key); properties.setProperty(key,value); properties.store(os,null); os.flush(); is.close(); os.close(); }catch(IOExceptione){ LOG.error("propertiesfilestreamcloseerror",e); } } /** * *getAllProperties:Readthepropertiesofalltheinformation<br/> *@returnpropertiesinformation */ @SuppressWarnings("rawtypes") publicStringgetAllProperties(){ Enumerationen=properties.propertyNames(); StringBuffersf=newStringBuffer(); while(en.hasMoreElements()){ Stringkey=(String)en.nextElement(); Stringvalue=properties.getProperty(key); sf.append("\n"+key); sf.append("="); value=value.replace(":","\\:"); sf.append(value); } returnsf.toString(); } }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。