配色: 字号:
20个非常实用的Java程序代码片段
2016-03-30 | 阅:  转:  |  分享 
  
字符串有整型的相互转换http://www.jb51.net/article/80081.htm?12Stringa=String.v
alueOf(2);?//integertonumericstringinti=Integer.parseInt(
a);//numericstringtoanint2.向文件末尾添加内容http://www.jb51.net/art
icle/80081.htm?1234567891011BufferedWriterout=null;try{?out
=newBufferedWriter(newFileWriter(”filename”,true));?out.wri
te(”aString”);}catch(IOExceptione){?//errorprocessingcod
e}finally{?if(out!=null){?out.close();?}}3.得到当前方法的名字h
ttp://www.jb51.net/article/80081.htm?1StringmethodName=Thread.
currentThread().getStackTrace()[1].getMethodName();4.转字符串到日期http
://www.jb51.net/article/80081.htm?1234java.util.Date=java.text.
DateFormat.getDateInstance().parse(dateString);或者是:SimpleDateFor
matformat=newSimpleDateFormat("dd.MM.yyyy");Datedate=fo
rmat.parse(myString);5.使用JDBC链接Oraclehttp://www.jb51.net/artic
le/80081.htm?1234567891011121314151617181920212223242526272829303
132333435363738publicclassOracleJdbcTest{?StringdriverClass
="oracle.jdbc.driver.OracleDriver";??Connectioncon;??publicv
oidinit(FileInputStreamfs)throwsClassNotFoundException,SQLEx
ception,FileNotFoundException,IOException?{?Propertiesprops
=newProperties();?props.load(fs);?Stringurl=props.getPrope
rty("db.url");?StringuserName=props.getProperty("db.user");?
Stringpassword=props.getProperty("db.password");?Class.forNam
e(driverClass);??con=DriverManager.getConnection(url,userName,
password);?}??publicvoidfetch()throwsSQLException,IOExcept
ion?{?PreparedStatementps=con.prepareStatement("selectSYSDA
TEfromdual");?ResultSetrs=ps.executeQuery();??while(rs.ne
xt())?{?//dothethingyoudo?}?rs.close();?ps.close();?}
??publicstaticvoidmain(String[]args)?{?OracleJdbcTesttest
=newOracleJdbcTest();?test.init();?test.fetch();?}}6.把Jav
autil.Date转成sql.Datehttp://www.jb51.net/article/80081.htm?12ja
va.util.DateutilDate=newjava.util.Date();java.sql.DatesqlDa
te=newjava.sql.Date(utilDate.getTime());7.使用NIO进行快速的文件拷贝http:
//www.jb51.net/article/80081.htm?12345678910111213141516171819202
1222324252627282930publicstaticvoidfileCopy(Filein,Fileout
)?throwsIOException?{?FileChannelinChannel=newFileInputS
tream(in).getChannel();?FileChanneloutChannel=newFileOutpu
tStream(out).getChannel();?try?{//????inChannel.transferTo(0
,inChannel.size(),outChannel);??//original--apparentlyhas
troublecopyinglargefilesonWindows??//magicnumberforWind
ows,64Mb-32Kb)?intmaxCount=(6410241024)-(321024
);?longsize=inChannel.size();?longposition=0;?while(po
sitionaxCount,outChannel);?}?}?finally?{?if(inChannel!=null)
?{?inChannel.close();?}?if(outChannel!=null)?{?outChan
nel.close();?}?}?}8.创建图片的缩略图http://www.jb51.net/article/80081
.htm?123456789101112131415161718192021222324252627282930313233343
5363738privatevoidcreateThumbnail(Stringfilename,intthumbWid
th,intthumbHeight,intquality,StringoutFilename)?throwsInt
erruptedException,FileNotFoundException,IOException?{?//load
imagefromfilename?Imageimage=Toolkit.getDefaultToolkit().g
etImage(filename);?MediaTrackermediaTracker=newMediaTracker(
newContainer());?mediaTracker.addImage(image,0);?mediaTracker
.waitForID(0);?//usethistotestforerrorsatthispoint:Sys
tem.out.println(mediaTracker.isErrorAny());??//determinethumbn
ailsizefromWIDTHandHEIGHT?doublethumbRatio=(double)thumb
Width/(double)thumbHeight;?intimageWidth=image.getWidth(nul
l);?intimageHeight=image.getHeight(null);?doubleimageRatio
=(double)imageWidth/(double)imageHeight;?if(thumbRatiogeRatio){?thumbHeight=(int)(thumbWidth/imageRatio);?}else
{?thumbWidth=(int)(thumbHeightimageRatio);?}??//drawor
iginalimagetothumbnailimageobjectand?//scaleittothene
wsizeon-the-fly?BufferedImagethumbImage=newBufferedImage(t
humbWidth,thumbHeight,BufferedImage.TYPE_INT_RGB);?Graphics2D
graphics2D=thumbImage.createGraphics();?graphics2D.setRenderin
gHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTE
RPOLATION_BILINEAR);?graphics2D.drawImage(image,0,0,thumbWidt
h,thumbHeight,null);??//savethumbnailimagetooutFilename?
BufferedOutputStreamout=newBufferedOutputStream(newFileOutpu
tStream(outFilename));?JPEGImageEncoderencoder=JPEGCodec.crea
teJPEGEncoder(out);?JPEGEncodeParamparam=encoder.getDefaultJP
EGEncodeParam(thumbImage);?quality=Math.max(0,Math.min(qualit
y,100));?param.setQuality((float)quality/100.0f,false);?enc
oder.setJPEGEncodeParam(param);?encoder.encode(thumbImage);?out
.close();?}9.创建JSON格式的数据并下面这个JAR文件:json-rpc-1.0.jar(75kb)h
ttp://www.jb51.net/article/80081.htm?123456789importorg.json.JSO
NObject;......JSONObjectjson=newJSONObject();json.put("ci
ty","Mumbai");json.put("country","India");...Stringoutput=
json.toString();...10.使用iTextJAR生成PDFhttp://www.jb51.net/arti
cle/80081.htm?123456789101112131415161718192021222324252627282930
importjava.io.File;importjava.io.FileOutputStream;importjava
.io.OutputStream;importjava.util.Date;?importcom.lowagie.text
.Document;importcom.lowagie.text.Paragraph;importcom.lowagie.
text.pdf.PdfWriter;?publicclassGeneratePDF{??publicstaticv
oidmain(String[]args){?try{?OutputStreamfile=newFileOut
putStream(newFile("C:\\Test.pdf"));??Documentdocument=newDo
cument();?PdfWriter.getInstance(document,file);?document.open(
);?document.add(newParagraph("HelloKiran"));?document.add(new
Paragraph(newDate().toString()));??document.close();?file.clo
se();??}catch(Exceptione){??e.printStackTrace();?}?}}11.
HTTP代理设置System.getProperties().put("http.proxyHost","someProxy
URL");?System.getProperties().put("http.proxyPort","someProxyPo
rt");?System.getProperties().put("http.proxyUser","someUserName
");?System.getProperties().put("http.proxyPassword","somePasswo
rd");12.单实例Singleton示例http://www.jb51.net/article/80081.htm?123
4567891011121314publicclassSimpleSingleton{?privatestaticSi
mpleSingletonsingleInstance=newSimpleSingleton();??//Marking
defaultconstructorprivate?//toavoiddirectinstantiation.?p
rivateSimpleSingleton(){?}??//GetinstanceforclassSimpleSi
ngleton?publicstaticSimpleSingletongetInstance(){??returns
ingleInstance;?}}另一种实现http://www.jb51.net/article/80081.htm?123
45678publicenumSimpleSingleton{?INSTANCE;?publicvoiddoSome
thing(){?}}?//CallthemethodfromSingleton:SimpleSingleton
.INSTANCE.doSomething();13.抓屏程序http://www.jb51.net/article/80081
.htm?1234567891011121314151617181920importjava.awt.Dimension;im
portjava.awt.Rectangle;importjava.awt.Robot;importjava.awt.T
oolkit;importjava.awt.image.BufferedImage;importjavax.imageio
.ImageIO;importjava.io.File;?...?publicvoidcaptureScreen(St
ringfileName)throwsException{??DimensionscreenSize=Toolki
t.getDefaultToolkit().getScreenSize();?RectanglescreenRectangle
=newRectangle(screenSize);?Robotrobot=newRobot();?Buffer
edImageimage=robot.createScreenCapture(screenRectangle);?Imag
eIO.write(image,"png",newFile(fileName));?}...14.列出文件和目录htt
p://www.jb51.net/article/80081.htm?123456789101112131415161718192
021222324252627282930Filedir=newFile("directoryName");?Strin
g[]children=dir.list();?if(children==null){?//Eitherdi
rdoesnotexistorisnotadirectory?}else{?for(inti=0;i
?Stringfilename=children[i];?}?}??//Itisalsopossibleto
filterthelistofreturnedfiles.?//Thisexampledoesnotret
urnanyfilesthatstartwith`.''.?FilenameFilterfilter=newF
ilenameFilter(){?publicbooleanaccept(Filedir,Stringname){
?return!name.startsWith(".");?}?};?children=dir.list(filte
r);??//ThelistoffilescanalsoberetrievedasFileobjects
?File[]files=dir.listFiles();??//Thisfilteronlyreturnsdi
rectories?FileFilterfileFilter=newFileFilter(){?publicboo
leanaccept(Filefile){?returnfile.isDirectory();?}?};?file
s=dir.listFiles(fileFilter);15.创建ZIP和JAR文件http://www.jb51.net/
article/80081.htm?12345678910111213141516171819202122232425262728
29303132333435363738394041424344454647484950importjava.util.zip.
;importjava.io.;?publicclassZipIt{?publicstaticvoidma
in(Stringargs[])throwsIOException{?if(args.length<2){?S
ystem.err.println("usage:javaZipItZip.zipfile1file2file3");
?System.exit(-1);?}?FilezipFile=newFile(args[0]);?if(zip
File.exists()){?System.err.println("Zipfilealreadyexists,pl
easetryanother");?System.exit(-2);?}?FileOutputStreamfos=
newFileOutputStream(zipFile);?ZipOutputStreamzos=newZipOutp
utStream(fos);?intbytesRead;?byte[]buffer=newbyte[1024];?
CRC32crc=newCRC32();?for(inti=1,n=args.length;i){?Stringname=args[i];?Filefile=newFile(name);?if(!fi
le.exists()){?System.err.println("Skipping:"+name);?continu
e;?}?BufferedInputStreambis=newBufferedInputStream(?newFi
leInputStream(file));?crc.reset();?while((bytesRead=bis.read
(buffer))!=-1){?crc.update(buffer,0,bytesRead);?}?bis.clo
se();?//Resettobeginningofinputstream?bis=newBufferedI
nputStream(?newFileInputStream(file));?ZipEntryentry=newZi
pEntry(name);?entry.setMethod(ZipEntry.STORED);?entry.setCompre
ssedSize(file.length());?entry.setSize(file.length());?entry.se
tCrc(crc.getValue());?zos.putNextEntry(entry);?while((bytesRea
d=bis.read(buffer))!=-1){?zos.write(buffer,0,bytesRead);
?}?bis.close();?}?zos.close();?}}16.解析/读取XML文件XML文件http://
www.jb51.net/article/80081.htm?123456789101112131415161718ersion="1.0"?>??John?B
?12?
??Mary
?A?11?
??S
imon
?A?18?
ts>Java代码http://www.jb51.net/article/80081.htm?123456789101112131
41516171819202122232425262728293031323334353637383940414243444546
474849505152535455565758596061626364656667686970717273packagenet
.viralpatel.java.xmlparser;?importjava.io.File;importjavax.xm
l.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuild
erFactory;?importorg.w3c.dom.Document;importorg.w3c.dom.Eleme
nt;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;?public
classXMLParser{??publicvoidgetAllUserNames(StringfileName)
{?try{?DocumentBuilderFactorydbf=DocumentBuilderFactory.ne
wInstance();?DocumentBuilderdb=dbf.newDocumentBuilder();?Fil
efile=newFile(fileName);?if(file.exists()){?Documentdoc
=db.parse(file);?ElementdocEle=doc.getDocumentElement();??/
/Printrootelementofthedocument?System.out.println("Rootel
ementofthedocument:"?+docEle.getNodeName());??NodeListstud
entList=docEle.getElementsByTagName("student");??//Printtota
lstudentelementsindocument?System.out?.println("Totalstude
nts:"+studentList.getLength());??if(studentList!=null&&s
tudentList.getLength()>0){?for(inti=0;itLength();i++){??Nodenode=studentList.item(i);??if(node.g
etNodeType()==Node.ELEMENT_NODE){??System.out?.println("====
=================");??Elemente=(Element)node;?NodeListnode
List=e.getElementsByTagName("name");?System.out.println("Name:
"?+nodeList.item(0).getChildNodes().item(0)?.getNodeValue());
??nodeList=e.getElementsByTagName("grade");?System.out.println
("Grade:"?+nodeList.item(0).getChildNodes().item(0)?.getNodeVa
lue());??nodeList=e.getElementsByTagName("age");?System.out.p
rintln("Age:"?+nodeList.item(0).getChildNodes().item(0)?.getNo
deValue());?}?}?}else{?System.exit(1);?}?}?}catch(Exce
ptione){?System.out.println(e);?}?}?publicstaticvoidmain
(String[]args){??XMLParserparser=newXMLParser();?parser.g
etAllUserNames("c:\\test.xml");?}}17.把Array转换成Maphttp://ww
w.jb51.net/article/80081.htm?123456789101112131415importjava.uti
l.Map;importorg.apache.commons.lang.ArrayUtils;?publicclassM
ain{??publicstaticvoidmain(String[]args){?String[][]coun
tries={{"UnitedStates","NewYork"},{"UnitedKingdom","L
ondon"},?{"Netherland","Amsterdam"},{"Japan","Tokyo"},{
"France","Paris"}};??MapcountryCapitals=ArrayUtils.toMap(
countries);??System.out.println("CapitalofJapanis"+country
Capitals.get("Japan"));?System.out.println("CapitalofFranceis
"+countryCapitals.get("France"));?}}18.发送邮件http://www.jb51.
net/article/80081.htm?1234567891011121314151617181920212223242526
272829303132333435363738importjavax.mail.;importjavax.mail.in
ternet.;importjava.util.;?publicvoidpostMail(Stringrecip
ients[],Stringsubject,Stringmessage,Stringfrom)throwsMe
ssagingException{?booleandebug=false;??//Setthehostsmtp
address?Propertiesprops=newProperties();?props.put("mail.sm
tp.host","smtp.example.com");??//createsomepropertiesandge
tthedefaultSession?Sessionsession=Session.getDefaultInstan
ce(props,null);?session.setDebug(debug);??//createamessage
?Messagemsg=newMimeMessage(session);??//setthefromandto
address?InternetAddressaddressFrom=newInternetAddress(from)
;?msg.setFrom(addressFrom);??InternetAddress[]addressTo=new
InternetAddress[recipients.length];?for(inti=0;its.length;i++)?{?addressTo[i]=newInternetAddress(recipients
[i]);?}?msg.setRecipients(Message.RecipientType.TO,addressTo);
??//Optional:YoucanalsosetyourcustomheadersintheEmai
lifyouWant?msg.addHeader("MyHeaderName","myHeaderValue");??
//SettingtheSubjectandContentType?msg.setSubject(subject);
?msg.setContent(message,"text/plain");?Transport.send(msg);}1
9.发送代数据的HTTP请求http://www.jb51.net/article/80081.htm?12345678910
1112131415161718importjava.io.BufferedReader;importjava.io.Inp
utStreamReader;importjava.net.URL;?publicclassMain{?public
staticvoidmain(String[]args){?try{?URLmy_url=newURL("
http://coolshell.cn/http://coolshell.cn/");?BufferedReaderbr=
newBufferedReader(newInputStreamReader(my_url.openStream()));?
StringstrTemp="";?while(null!=(strTemp=br.readLine())){?
System.out.println(strTemp);?}?}catch(Exceptionex){?ex.printStackTrace();?}?}}20.改变数组的大小http://www.jb51.net/article/80081.htm?123456789101112131415161718192021222324252627/Reallocatesanarraywithanewsize,andcopiesthecontentsoftheoldarraytothenewarray.@paramoldArraytheoldarray,tobereallocated.@paramnewSize?thenewarraysize.@return????Anewarraywiththesamecontents./privatestaticObjectresizeArray(ObjectoldArray,intnewSize){?intoldSize=java.lang.reflect.Array.getLength(oldArray);?ClasselementType=oldArray.getClass().getComponentType();?ObjectnewArray=java.lang.reflect.Array.newInstance(?elementType,newSize);?intpreserveLength=Math.min(oldSize,newSize);?if(preserveLength>0)?System.arraycopy(oldArray,0,newArray,0,preserveLength);?returnnewArray;}?//TestroutineforresizeArray().publicstaticvoidmain(String[]args){?int[]a={1,2,3};?a=(int[])resizeArray(a,5);?a[3]=4;?a[4]=5;?for(inti=0;i
献花(0)
+1
(本文系莫言jack首藏)