`
天边一朵雲
  • 浏览: 34956 次
  • 性别: Icon_minigender_1
  • 来自: 成都
社区版块
存档分类
最新评论

20个非常有用的Java程序片段

 
阅读更多
1. 字符串有整型的相互转换
Java代码
  1. Stringa=String.valueOf(2);//integertonumericstring
  2. inti=Integer.parseInt(a);//numericstringtoanint


2. 向文件末尾添加内容
Java代码
  1. BufferedWriterout=null;
  2. try{
  3. out=newBufferedWriter(newFileWriter(”filename”,true));
  4. out.write(”aString”);
  5. }catch(IOExceptione){
  6. //errorprocessingcode
  7. }finally{
  8. if(out!=null){
  9. 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代码
  1. publicclassOracleJdbcTest
  2. {
  3. StringdriverClass="oracle.jdbc.driver.OracleDriver";
  4. Connectioncon;
  5. publicvoidinit(FileInputStreamfs)throwsClassNotFoundException,SQLException,FileNotFoundException,IOException
  6. {
  7. Propertiesprops=newProperties();
  8. props.load(fs);
  9. 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代码
  1. publicstaticvoidfileCopy(Filein,Fileout)
  2. throwsIOException
  3. {
  4. FileChannelinChannel=newFileInputStream(in).getChannel();
  5. FileChanneloutChannel=newFileOutputStream(out).getChannel();
  6. try
  7. {
  8. //inChannel.transferTo(0,inChannel.size(),outChannel);//original--apparentlyhastroublecopyinglargefilesonWindows
  9. //magicnumberforWindows,64Mb-32Kb)
  10. intmaxCount=(64*1024*1024)-(32*1024);
  11. longsize=inChannel.size();
  12. longposition=0;
  13. while(position<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代码
  1. privatevoidcreateThumbnail(Stringfilename,intthumbWidth,intthumbHeight,intquality,StringoutFilename)
  2. throwsInterruptedException,FileNotFoundException,IOException
  3. {
  4. //loadimagefromfilename
  5. Imageimage=Toolkit.getDefaultToolkit().getImage(filename);
  6. MediaTrackermediaTracker=newMediaTracker(newContainer());
  7. mediaTracker.addImage(image,0);
  8. mediaTracker.waitForID(0);
  9. //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<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代码
  1. importjava.io.File;
  2. importjava.io.FileOutputStream;
  3. importjava.io.OutputStream;
  4. importjava.util.Date;
  5. importcom.lowagie.text.Document;
  6. importcom.lowagie.text.Paragraph;
  7. importcom.lowagie.text.pdf.PdfWriter;
  8. publicclassGeneratePDF{
  9. 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代码
  1. publicclassSimpleSingleton{
  2. privatestaticSimpleSingletonsingleInstance=newSimpleSingleton();
  3. //Markingdefaultconstructorprivate
  4. //toavoiddirectinstantiation.
  5. privateSimpleSingleton(){
  6. }
  7. //GetinstanceforclassSimpleSingleton
  8. publicstaticSimpleSingletongetInstance(){
  9. returnsingleInstance;
  10. }
  11. }


另一种实现:
Java代码
  1. publicenumSimpleSingleton{
  2. INSTANCE;
  3. publicvoiddoSomething(){
  4. }
  5. }
  6. //CallthemethodfromSingleton:
  7. SimpleSingleton.INSTANCE.doSomething();


13. 抓屏程序
Java代码
  1. importjava.awt.Dimension;
  2. importjava.awt.Rectangle;
  3. importjava.awt.Robot;
  4. importjava.awt.Toolkit;
  5. importjava.awt.image.BufferedImage;
  6. importjavax.imageio.ImageIO;
  7. importjava.io.File;
  8. ...
  9. 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代码
  1. Filedir=newFile("directoryName");
  2. String[]children=dir.list();
  3. if(children==null){
  4. //Eitherdirdoesnotexistorisnotadirectory
  5. }else{
  6. for(inti=0;i<children.length;i++){
  7. //Getfilenameoffileordirectory
  8. Stringfilename=children[i];
  9. }
  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代码
  1. importjava.util.zip.*;
  2. importjava.io.*;
  3. publicclassZipIt{
  4. publicstaticvoidmain(Stringargs[])throwsIOException{
  5. if(args.length<2){
  6. System.err.println("usage:javaZipItZip.zipfile1file2file3");
  7. System.exit(-1);
  8. }
  9. 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<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代码
  1. <?xmlversion="1.0"?>
  2. <students>
  3. <student>
  4. <name>John</name>
  5. <grade>B</grade>
  6. <age>12</age>
  7. </student>
  8. <student>
  9. <name>Mary</name>
  10. <grade>A</grade>
  11. <age>11</age>
  12. </student>
  13. <student>
  14. <name>Simon</name>
  15. <grade>A</grade>
  16. <age>18</age>
  17. </student>
  18. </students>


Java代码
  1. packagenet.viralpatel.java.xmlparser;
  2. importjava.io.File;
  3. importjavax.xml.parsers.DocumentBuilder;
  4. importjavax.xml.parsers.DocumentBuilderFactory;
  5. importorg.w3c.dom.Document;
  6. importorg.w3c.dom.Element;
  7. importorg.w3c.dom.Node;
  8. importorg.w3c.dom.NodeList;
  9. 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()>0){
  26. for(inti=0;i<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代码
  1. importjava.util.Map;
  2. importorg.apache.commons.lang.ArrayUtils;
  3. publicclassMain{
  4. publicstaticvoidmain(String[]args){
  5. String[][]countries={{"UnitedStates","NewYork"},{"UnitedKingdom","London"},
  6. {"Netherland","Amsterdam"},{"Japan","Tokyo"},{"France","Paris"}};
  7. MapcountryCapitals=ArrayUtils.toMap(countries);
  8. System.out.println("CapitalofJapanis"+countryCapitals.get("Japan"));
  9. System.out.println("CapitalofFranceis"+countryCapitals.get("France"));
  10. }
  11. }


18. 发送邮件
Java代码
  1. importjavax.mail.*;
  2. importjavax.mail.internet.*;
  3. importjava.util.*;
  4. publicvoidpostMail(Stringrecipients[],Stringsubject,Stringmessage,Stringfrom)throwsMessagingException
  5. {
  6. booleandebug=false;
  7. //Setthehostsmtpaddress
  8. Propertiesprops=newProperties();
  9. 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<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代码
  1. importjava.io.BufferedReader;
  2. importjava.io.InputStreamReader;
  3. importjava.net.URL;
  4. publicclassMain{
  5. publicstaticvoidmain(String[]args){
  6. try{
  7. URLmy_url=newURL("http://coolshell.cn/");
  8. BufferedReaderbr=newBufferedReader(newInputStreamReader(my_url.openStream()));
  9. StringstrTemp="";
  10. while(null!=(strTemp=br.readLine())){
  11. System.out.println(strTemp);
  12. }
  13. }catch(Exceptionex){
  14. ex.printStackTrace();
  15. }
  16. }
  17. }


20. 改变数组的大小

Java代码
  1. /**
  2. *Reallocatesanarraywithanewsize,andcopiesthecontents
  3. *oftheoldarraytothenewarray.
  4. *@paramoldArraytheoldarray,tobereallocated.
  5. *@paramnewSizethenewarraysize.
  6. *@returnAnewarraywiththesamecontents.
  7. */
  8. privatestaticObjectresizeArray(ObjectoldArray,intnewSize){
  9. 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>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<a.length;i++)
  25. System.out.println(a[i]);
  26. }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics