---
title: "20个非常有用的Java程序片段"
author: "天边一朵雲"
date: "2012-07-05T22:00:00Z"
tags: []
slug: "20-java"
draft: false
lastmod: "2012-12-24T09:06:25Z"
id: 1752802
url: "https://itexpress.iteye.com/blog/1752802"
---

**1. 字符串有整型的相互转换**

Java代码

1. Stringa=String.valueOf(2);//integertonumericstring
2. inti=Integer.parseInt(a);//numericstringtoanint

**2. 向文件末尾添加内容**

Java代码

01. BufferedWriterout=null;
02. try{
03. out=newBufferedWriter(newFileWriter(”filename”,true));
04. out.write(”aString”);
05. }catch(IOExceptione){
06. //errorprocessingcode
07. }finally{
08. if(out!=null){
09. out.close();
10. }
11. }

**3. 得到当前方法的名字**

Java代码

1. StringmethodName=Thread.currentThread().getStackTrace()\[1].getMethodName();

**4. 转字符串到日期**

Java代码

1. java.util.Date=java.text.DateFormat.getDateInstance().parse(dateString);

或者是：

Java代码

1. SimpleDateFormatformat=newSimpleDateFormat("dd.MM.yyyy");
2. Datedate=format.parse(myString);

**5. 使用JDBC链接Oracle**

Java代码

01. publicclassOracleJdbcTest
02. {
03. StringdriverClass="oracle.jdbc.driver.OracleDriver";
04. Connectioncon;
05. publicvoidinit(FileInputStreamfs)throwsClassNotFoundException,SQLException,FileNotFoundException,IOException
06. {
07. Propertiesprops=newProperties();
08. props.load(fs);
09. Stringurl=props.getProperty("db.url");
10. StringuserName=props.getProperty("db.user");
11. Stringpassword=props.getProperty("db.password");
12. Class.forName(driverClass);
13. con=DriverManager.getConnection(url,userName,password);
14. }
15. publicvoidfetch()throwsSQLException,IOException
16. {
17. PreparedStatementps=con.prepareStatement("selectSYSDATEfromdual");
18. ResultSetrs=ps.executeQuery();
19. while(rs.next())
20. {
21. //dothethingyoudo
22. }
23. rs.close();
24. ps.close();
25. }
26. publicstaticvoidmain(String\[]args)
27. {
28. OracleJdbcTesttest=newOracleJdbcTest();
29. test.init();
30. test.fetch();
31. }
32. }

**6. 把 Java util.Date 转成 sql.Date**

Java代码

1. java.util.DateutilDate=newjava.util.Date();
2. java.sql.DatesqlDate=newjava.sql.Date(utilDate.getTime());

**7. 使用NIO进行快速的文件拷贝**

Java代码

01. publicstaticvoidfileCopy(Filein,Fileout)
02. throwsIOException
03. {
04. FileChannelinChannel=newFileInputStream(in).getChannel();
05. FileChanneloutChannel=newFileOutputStream(out).getChannel();
06. try
07. {
08. //inChannel.transferTo(0,inChannel.size(),outChannel);//original--apparentlyhastroublecopyinglargefilesonWindows
09. //magicnumberforWindows,64Mb-32Kb)
10. intmaxCount=(64\*1024\*1024)-(32\*1024);
11. longsize=inChannel.size();
12. longposition=0;
13. while(position&lt;size)
14. {
15. position+=inChannel.transferTo(position,maxCount,outChannel);
16. }
17. }
18. finally
19. {
20. if(inChannel!=null)
21. {
22. inChannel.close();
23. }
24. if(outChannel!=null)
25. {
26. outChannel.close();
27. }
28. }
29. }

**8. 创建图片的缩略图**

Java代码

01. privatevoidcreateThumbnail(Stringfilename,intthumbWidth,intthumbHeight,intquality,StringoutFilename)
02. throwsInterruptedException,FileNotFoundException,IOException
03. {
04. //loadimagefromfilename
05. Imageimage=Toolkit.getDefaultToolkit().getImage(filename);
06. MediaTrackermediaTracker=newMediaTracker(newContainer());
07. mediaTracker.addImage(image,0);
08. mediaTracker.waitForID(0);
09. //usethistotestforerrorsatthispoint:System.out.println(mediaTracker.isErrorAny());
10. //determinethumbnailsizefromWIDTHandHEIGHT
11. doublethumbRatio=(double)thumbWidth/(double)thumbHeight;
12. intimageWidth=image.getWidth(null);
13. intimageHeight=image.getHeight(null);
14. doubleimageRatio=(double)imageWidth/(double)imageHeight;
15. if(thumbRatio&lt;imageRatio){
16. thumbHeight=(int)(thumbWidth/imageRatio);
17. }else{
18. thumbWidth=(int)(thumbHeight\*imageRatio);
19. }
20. //draworiginalimagetothumbnailimageobjectand
21. //scaleittothenewsizeon-the-fly
22. BufferedImagethumbImage=newBufferedImage(thumbWidth,thumbHeight,BufferedImage.TYPE\_INT\_RGB);
23. Graphics2Dgraphics2D=thumbImage.createGraphics();
24. graphics2D.setRenderingHint(RenderingHints.KEY\_INTERPOLATION,RenderingHints.VALUE\_INTERPOLATION\_BILINEAR);
25. graphics2D.drawImage(image,0,0,thumbWidth,thumbHeight,null);
26. //savethumbnailimagetooutFilename
27. BufferedOutputStreamout=newBufferedOutputStream(newFileOutputStream(outFilename));
28. JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out);
29. JPEGEncodeParamparam=encoder.getDefaultJPEGEncodeParam(thumbImage);
30. quality=Math.max(0,Math.min(quality,100));
31. param.setQuality((float)quality/100.0f,false);
32. encoder.setJPEGEncodeParam(param);
33. encoder.encode(thumbImage);
34. out.close();
35. }

**9. 创建 JSON 格式的数据**

Java代码

1. importorg.json.JSONObject;
2. ...
3. ...
4. JSONObjectjson=newJSONObject();
5. json.put("city","Mumbai");
6. json.put("country","India");
7. ...
8. Stringoutput=json.toString();
9. ...

**10. 使用iText JAR生成PDF**

Java代码

01. importjava.io.File;
02. importjava.io.FileOutputStream;
03. importjava.io.OutputStream;
04. importjava.util.Date;
05. importcom.lowagie.text.Document;
06. importcom.lowagie.text.Paragraph;
07. importcom.lowagie.text.pdf.PdfWriter;
08. publicclassGeneratePDF{
09. publicstaticvoidmain(String\[]args){
10. try{
11. OutputStreamfile=newFileOutputStream(newFile("C:\\\\Test.pdf"));
12. Documentdocument=newDocument();
13. PdfWriter.getInstance(document,file);
14. document.open();
15. document.add(newParagraph("HelloKiran"));
16. document.add(newParagraph(newDate().toString()));
17. document.close();
18. file.close();
19. }catch(Exceptione){
20. e.printStackTrace();
21. }
22. }
23. }

**11. HTTP 代理设置**

Java代码

1. System.getProperties().put("http.proxyHost","someProxyURL");
2. System.getProperties().put("http.proxyPort","someProxyPort");
3. System.getProperties().put("http.proxyUser","someUserName");
4. System.getProperties().put("http.proxyPassword","somePassword");

**12. 单实例Singleton 示例**

Java代码

01. publicclassSimpleSingleton{
02. privatestaticSimpleSingletonsingleInstance=newSimpleSingleton();
03. //Markingdefaultconstructorprivate
04. //toavoiddirectinstantiation.
05. privateSimpleSingleton(){
06. }
07. //GetinstanceforclassSimpleSingleton
08. publicstaticSimpleSingletongetInstance(){
09. returnsingleInstance;
10. }
11. }

另一种实现：

Java代码

1. publicenumSimpleSingleton{
2. INSTANCE;
3. publicvoiddoSomething(){
4. }
5. }
6. //CallthemethodfromSingleton:
7. SimpleSingleton.INSTANCE.doSomething();

**13. 抓屏程序**

Java代码

01. importjava.awt.Dimension;
02. importjava.awt.Rectangle;
03. importjava.awt.Robot;
04. importjava.awt.Toolkit;
05. importjava.awt.image.BufferedImage;
06. importjavax.imageio.ImageIO;
07. importjava.io.File;
08. ...
09. publicvoidcaptureScreen(StringfileName)throwsException{
10. DimensionscreenSize=Toolkit.getDefaultToolkit().getScreenSize();
11. RectanglescreenRectangle=newRectangle(screenSize);
12. Robotrobot=newRobot();
13. BufferedImageimage=robot.createScreenCapture(screenRectangle);
14. ImageIO.write(image,"png",newFile(fileName));
15. }
16. ...

**14. 列出文件和目录**

Java代码

01. Filedir=newFile("directoryName");
02. String\[]children=dir.list();
03. if(children==null){
04. //Eitherdirdoesnotexistorisnotadirectory
05. }else{
06. for(inti=0;i&lt;children.length;i++){
07. //Getfilenameoffileordirectory
08. Stringfilename=children\[i];
09. }
10. }
11. //Itisalsopossibletofilterthelistofreturnedfiles.
12. //Thisexampledoesnotreturnanyfilesthatstartwith\`.'.
13. FilenameFilterfilter=newFilenameFilter(){
14. publicbooleanaccept(Filedir,Stringname){
15. return!name.startsWith(".");
16. }
17. };
18. children=dir.list(filter);
19. //ThelistoffilescanalsoberetrievedasFileobjects
20. File\[]files=dir.listFiles();
21. //Thisfilteronlyreturnsdirectories
22. FileFilterfileFilter=newFileFilter(){
23. publicbooleanaccept(Filefile){
24. returnfile.isDirectory();
25. }
26. };
27. files=dir.listFiles(fileFilter);

**15. 创建ZIP和JAR文件**

Java代码

01. importjava.util.zip.\*;
02. importjava.io.\*;
03. publicclassZipIt{
04. publicstaticvoidmain(Stringargs\[])throwsIOException{
05. if(args.length&lt;2){
06. System.err.println("usage:javaZipItZip.zipfile1file2file3");
07. System.exit(-1);
08. }
09. FilezipFile=newFile(args\[0]);
10. if(zipFile.exists()){
11. System.err.println("Zipfilealreadyexists,pleasetryanother");
12. System.exit(-2);
13. }
14. FileOutputStreamfos=newFileOutputStream(zipFile);
15. ZipOutputStreamzos=newZipOutputStream(fos);
16. intbytesRead;
17. byte\[]buffer=newbyte\[1024];
18. CRC32crc=newCRC32();
19. for(inti=1,n=args.length;i&lt;n;i++){
20. Stringname=args\[i];
21. Filefile=newFile(name);
22. if(!file.exists()){
23. System.err.println("Skipping:"+name);
24. continue;
25. }
26. BufferedInputStreambis=newBufferedInputStream(
27. newFileInputStream(file));
28. crc.reset();
29. while((bytesRead=bis.read(buffer))!=-1){
30. crc.update(buffer,0,bytesRead);
31. }
32. bis.close();
33. //Resettobeginningofinputstream
34. bis=newBufferedInputStream(
35. newFileInputStream(file));
36. ZipEntryentry=newZipEntry(name);
37. entry.setMethod(ZipEntry.STORED);
38. entry.setCompressedSize(file.length());
39. entry.setSize(file.length());
40. entry.setCrc(crc.getValue());
41. zos.putNextEntry(entry);
42. while((bytesRead=bis.read(buffer))!=-1){
43. zos.write(buffer,0,bytesRead);
44. }
45. bis.close();
46. }
47. zos.close();
48. }
49. }

**16. 解析/读取XML 文件**

XML文件

Xml代码

01. &lt;?xmlversion="1.0"?&gt;
02. &lt;students&gt;
03. &lt;student&gt;
04. &lt;name&gt;John&lt;/name&gt;
05. &lt;grade&gt;B&lt;/grade&gt;
06. &lt;age&gt;12&lt;/age&gt;
07. &lt;/student&gt;
08. &lt;student&gt;
09. &lt;name&gt;Mary&lt;/name&gt;
10. &lt;grade&gt;A&lt;/grade&gt;
11. &lt;age&gt;11&lt;/age&gt;
12. &lt;/student&gt;
13. &lt;student&gt;
14. &lt;name&gt;Simon&lt;/name&gt;
15. &lt;grade&gt;A&lt;/grade&gt;
16. &lt;age&gt;18&lt;/age&gt;
17. &lt;/student&gt;
18. &lt;/students&gt;

Java代码

01. packagenet.viralpatel.java.xmlparser;
02. importjava.io.File;
03. importjavax.xml.parsers.DocumentBuilder;
04. importjavax.xml.parsers.DocumentBuilderFactory;
05. importorg.w3c.dom.Document;
06. importorg.w3c.dom.Element;
07. importorg.w3c.dom.Node;
08. importorg.w3c.dom.NodeList;
09. publicclassXMLParser{
10. publicvoidgetAllUserNames(StringfileName){
11. try{
12. DocumentBuilderFactorydbf=DocumentBuilderFactory.newInstance();
13. DocumentBuilderdb=dbf.newDocumentBuilder();
14. Filefile=newFile(fileName);
15. if(file.exists()){
16. Documentdoc=db.parse(file);
17. ElementdocEle=doc.getDocumentElement();
18. //Printrootelementofthedocument
19. System.out.println("Rootelementofthedocument:"
20. +docEle.getNodeName());
21. NodeListstudentList=docEle.getElementsByTagName("student");
22. //Printtotalstudentelementsindocument
23. System.out
24. .println("Totalstudents:"+studentList.getLength());
25. if(studentList!=null&&studentList.getLength()&gt;0){
26. for(inti=0;i&lt;studentList.getLength();i++){
27. Nodenode=studentList.item(i);
28. if(node.getNodeType()==Node.ELEMENT\_NODE){
29. System.out
30. .println("=====================");
31. Elemente=(Element)node;
32. NodeListnodeList=e.getElementsByTagName("name");
33. System.out.println("Name:"
34. +nodeList.item(0).getChildNodes().item(0)
35. .getNodeValue());
36. nodeList=e.getElementsByTagName("grade");
37. System.out.println("Grade:"
38. +nodeList.item(0).getChildNodes().item(0)
39. .getNodeValue());
40. nodeList=e.getElementsByTagName("age");
41. System.out.println("Age:"
42. +nodeList.item(0).getChildNodes().item(0)
43. .getNodeValue());
44. }
45. }
46. }else{
47. System.exit(1);
48. }
49. }
50. }catch(Exceptione){
51. System.out.println(e);
52. }
53. }
54. publicstaticvoidmain(String\[]args){
55. XMLParserparser=newXMLParser();
56. parser.getAllUserNames("c:\\\\test.xml");
57. }
58. }

**17. 把 Array 转换成 Map**

Java代码

01. importjava.util.Map;
02. importorg.apache.commons.lang.ArrayUtils;
03. publicclassMain{
04. publicstaticvoidmain(String\[]args){
05. String\[]\[]countries={{"UnitedStates","NewYork"},{"UnitedKingdom","London"},
06. {"Netherland","Amsterdam"},{"Japan","Tokyo"},{"France","Paris"}};
07. MapcountryCapitals=ArrayUtils.toMap(countries);
08. System.out.println("CapitalofJapanis"+countryCapitals.get("Japan"));
09. System.out.println("CapitalofFranceis"+countryCapitals.get("France"));
10. }
11. }

**18. 发送邮件**

Java代码

01. importjavax.mail.\*;
02. importjavax.mail.internet.\*;
03. importjava.util.\*;
04. publicvoidpostMail(Stringrecipients\[],Stringsubject,Stringmessage,Stringfrom)throwsMessagingException
05. {
06. booleandebug=false;
07. //Setthehostsmtpaddress
08. Propertiesprops=newProperties();
09. props.put("mail.smtp.host","smtp.example.com");
10. //createsomepropertiesandgetthedefaultSession
11. Sessionsession=Session.getDefaultInstance(props,null);
12. session.setDebug(debug);
13. //createamessage
14. Messagemsg=newMimeMessage(session);
15. //setthefromandtoaddress
16. InternetAddressaddressFrom=newInternetAddress(from);
17. msg.setFrom(addressFrom);
18. InternetAddress\[]addressTo=newInternetAddress\[recipients.length];
19. for(inti=0;i&lt;recipients.length;i++)
20. {
21. addressTo\[i]=newInternetAddress(recipients\[i]);
22. }
23. msg.setRecipients(Message.RecipientType.TO,addressTo);
24. //Optional:YoucanalsosetyourcustomheadersintheEmailifyouWant
25. msg.addHeader("MyHeaderName","myHeaderValue");
26. //SettingtheSubjectandContentType
27. msg.setSubject(subject);
28. msg.setContent(message,"text/plain");
29. Transport.send(msg);
30. }

**19. 发送代数据的HTTP 请求**

Java代码

01. importjava.io.BufferedReader;
02. importjava.io.InputStreamReader;
03. importjava.net.URL;
04. publicclassMain{
05. publicstaticvoidmain(String\[]args){
06. try{
07. URLmy\_url=newURL("http://coolshell.cn/");
08. BufferedReaderbr=newBufferedReader(newInputStreamReader(my\_url.openStream()));
09. StringstrTemp="";
10. while(null!=(strTemp=br.readLine())){
11. System.out.println(strTemp);
12. }
13. }catch(Exceptionex){
14. ex.printStackTrace();
15. }
16. }
17. }

**20. 改变数组的大小**

Java代码

01. /\**
02. \*Reallocatesanarraywithanewsize,andcopiesthecontents
03. \*oftheoldarraytothenewarray.
04. \*@paramoldArraytheoldarray,tobereallocated.
05. \*@paramnewSizethenewarraysize.
06. \*@returnAnewarraywiththesamecontents.
07. \*/
08. privatestaticObjectresizeArray(ObjectoldArray,intnewSize){
09. intoldSize=java.lang.reflect.Array.getLength(oldArray);
10. ClasselementType=oldArray.getClass().getComponentType();
11. ObjectnewArray=java.lang.reflect.Array.newInstance(
12. elementType,newSize);
13. intpreserveLength=Math.min(oldSize,newSize);
14. if(preserveLength&gt;0)
15. System.arraycopy(oldArray,0,newArray,0,preserveLength);
16. returnnewArray;
17. }
18. //TestroutineforresizeArray().
19. publicstaticvoidmain(String\[]args){
20. int\[]a={1,2,3};
21. a=(int\[])resizeArray(a,5);
22. a\[3]=4;
23. a\[4]=5;
24. for(inti=0;i&lt;a.length;i++)
25. System.out.println(a\[i]);
26. }