20个非常有用的Java程序片段.docx
- 文档编号:30636528
- 上传时间:2023-08-18
- 格式:DOCX
- 页数:21
- 大小:21.15KB
20个非常有用的Java程序片段.docx
《20个非常有用的Java程序片段.docx》由会员分享,可在线阅读,更多相关《20个非常有用的Java程序片段.docx(21页珍藏版)》请在冰豆网上搜索。
20个非常有用的Java程序片段
1.字符串有整型的相互转换
Java代码
Stringa=String.valueOf
(2); //integertonumericstring
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代码
StringmethodName=Thread.currentThread().getStackTrace()[1].getMethodName();
4.转字符串到日期
Java代码
java.util.Date=java.text.DateFormat.getDateInstance().parse(dateString);
或者是:
SimpleDateFormatformat=newSimpleDateFormat("dd.MM.yyyy");
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.把Javautil.Date转成sql.Date
Java代码
java.util.DateutilDate=newjava.util.Date();
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--apparentlyhastroublecopyinglargefileson Windows
9. //magicnumberforWindows,64Mb-32Kb)
10. intmaxCount=(64*1024*1024)-(32*1024);
11. longsize=inChannel.size();
12. longposition=0;
13. while(position 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 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.使用iTextJAR生成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. } 复制代码 另一种实现 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. ... 17. 18. importjava.awt.Dimension; 19. importjava.awt.Rectangle; 20. importjava.awt.Robot; 21. importjava.awt.Toolkit; 22. importjava.awt.image.BufferedImage; 23. importjavax.imageio.ImageIO; 24. importjava.io.File; 25. ... 26. publicvoidcaptureScreen(StringfileName)throwsException{ 27. DimensionscreenSize=Toolkit.getDefaultToolkit().getScreenSize(); 28. RectanglescreenRectangle=newRectangle(screenSize); 29. Robotrobot=newRobot(); 30. BufferedImageimage=robot.createScreenCapture(screenRectangle); 31. ImageIO.write(image,"png",newFile(fileName)); 32. } 复制代码 14.列出文件和目录 Java代码 1. Filedir=newFile("directoryName"); 2. String[]children=dir.list(); 3. if(children==null){ 4. //Eitherdirdoesnotexistorisnotadirectory 5. }else{ 6. for(inti=0;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 20. Stringname=args[i]; 21. Filefile=newFile(name); 22. if(! file.exists()){ 23. System.err.println("Skipping: "+name); 24. continue; 25. } 26. Buf
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- 20 非常 有用 Java 程序 片段