20个JAVA人员非常有用的功能代码.docx

上传人:b****8 文档编号:9860435 上传时间:2023-05-21 格式:DOCX 页数:33 大小:24.92KB
下载 相关 举报
20个JAVA人员非常有用的功能代码.docx_第1页
第1页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第2页
第2页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第3页
第3页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第4页
第4页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第5页
第5页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第6页
第6页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第7页
第7页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第8页
第8页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第9页
第9页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第10页
第10页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第11页
第11页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第12页
第12页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第13页
第13页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第14页
第14页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第15页
第15页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第16页
第16页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第17页
第17页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第18页
第18页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第19页
第19页 / 共33页
20个JAVA人员非常有用的功能代码.docx_第20页
第20页 / 共33页
亲,该文档总共33页,到这儿已超出免费预览范围,如果喜欢就下载吧!
下载资源
资源描述

20个JAVA人员非常有用的功能代码.docx

《20个JAVA人员非常有用的功能代码.docx》由会员分享,可在线阅读,更多相关《20个JAVA人员非常有用的功能代码.docx(33页珍藏版)》请在冰点文库上搜索。

20个JAVA人员非常有用的功能代码.docx

20个JAVA人员非常有用的功能代码

本文将为大家介绍20人员非常有用的Java功能代码。

这20段代码,可以成为大家在今后的开发过程中,Java编程手册的重要部分。

1.把Strings转换成int和把int转换成String

1.Stringa=String.valueOf

(2);  //integertonumericstring

2.inti=Integer.parseInt(a);//numericstringtoanint

复制代码

2.向Java文件中添加文本

1.Updated:

ThanksSimoneforpointingtoexception.Ihave 

2.

3.changedthecode.  

4.

5.BufferedWriterout=null;

6.try{

7.out=newBufferedWriter(newFileWriter(”filename”,true));

8.out.write(”aString”);

9.}catch(IOExceptione){

10.//errorprocessingcode

11.}finally{

12.if(out!

=null){

13.out.close();

14.}

15.}

复制代码

3.获取Java现在正调用的方法名 

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

复制代码

4.在Java中将String型转换成Date型

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

2.or 

3.SimpleDateFormatformat=newSimpleDateFormat("dd.MM.yyyy");  

4.Datedate=format.parse(myString);

复制代码

5.通过JavaJDBC链接Oracle数据库

1.publicclassOracleJdbcTest

2.{

3.StringdriverClass="oracle.jdbc.driver.OracleDriver";

4.

5.Connectioncon;

6.

7.publicvoidinit(FileInputStreamfs)throwsClassNotFoundException,

8.

9.SQLException,FileNotFoundException,IOException

10.{

11.Propertiesprops=newProperties();

12.props.load(fs);

13.Stringurl=props.getProperty("db.url");

14.StringuserName=props.getProperty("db.user");

15.Stringpassword=props.getProperty("db.password");

16.Class.forName(driverClass);

17.

18.con=DriverManager.getConnection(url,userName,password);

19.}

20.

21.publicvoidfetch()throwsSQLException,IOException

22.{

23.PreparedStatementps=con.prepareStatement("selectSYSDATEfrom

24.

25.dual");

26.ResultSetrs=ps.executeQuery();

27.

28.while(rs.next())

29.{

30.//dothethingyoudo

31.}

32.rs.close();

33.ps.close();

34.}

35.

36.publicstaticvoidmain(String[]args)

37.{

38.OracleJdbcTesttest=newOracleJdbcTest();

39.test.init();

40.test.fetch();

41.}

42.}

复制代码

6.将Java中的util.Date转换成sql.Date

这一片段显示如何将一个javautilDate转换成sqlDate用于数据库

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

9.

10.--apparentlyhastroublecopyinglargefilesonWindows

11.

12.//magicnumberforWindows,64Mb-32Kb)

13.intmaxCount=(64*1024*1024)-(32*1024);

14.longsize=inChannel.size();

15.longposition=0;

16.while(position

17.{

18.  position+=inChannel.transferTo(position,maxCount,outChannel);

19.}

20.}

21.finally

22.{

23.if(inChannel!

=null)

24.{

25.  inChannel.close();

26.}

27.if(outChannel!

=null)

28.{

29.  outChannel.close();

30.}

31.}

32.}

复制代码

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

10.

11.(mediaTracker.isErrorAny());

12.

13.//determinethumbnailsizefromWIDTHandHEIGHT

14.doublethumbRatio=(double)thumbWidth/(double)thumbHeight;

15.intimageWidth=image.getWidth(null);

16.intimageHeight=image.getHeight(null);

17.doubleimageRatio=(double)imageWidth/(double)imageHeight;

18.if(thumbRatio

19.thumbHeight=(int)(thumbWidth/imageRatio);

20.}else{

21.thumbWidth=(int)(thumbHeight*imageRatio);

22.}

23.

24.//draworiginalimagetothumbnailimageobjectand

25.//scaleittothenewsizeon-the-fly

26.BufferedImagethumbImage=newBufferedImage(thumbWidth,

27.

28.thumbHeight,BufferedImage.TYPE_INT_RGB);

29.Graphics2Dgraphics2D=thumbImage.createGraphics();

30.graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,

31.

32.RenderingHints.VALUE_INTERPOLATION_BILINEAR);

33.graphics2D.drawImage(image,0,0,thumbWidth,thumbHeight,null);

34.

35.//savethumbnailimagetooutFilename

36.BufferedOutputStreamout=newBufferedOutputStream(new

37.

38.FileOutputStream(outFilename));

39.JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out);

40.JPEGEncodeParamparam=encoder.getDefaultJPEGEncodeParam

41.

42.(thumbImage);

43.quality=Math.max(0,Math.min(quality,100));

44.param.setQuality((float)quality/100.0f,false);

45.encoder.setJPEGEncodeParam(param);

46.encoder.encode(thumbImage);

47.out.close();

48.}

复制代码

9.在Java中创建JSON数据

1.Readthisarticleformoredetails.

2.DownloadJARfilejson

3.-rpc-1.0.jar(75kb)

4.importorg.json.JSONObject;

5....

6....

7.JSONObjectjson=newJSONObject();

8.json.put("city","Mumbai");

9.json.put("country","India");

10....

11.Stringoutput=json.toString();

12....

复制代码

10.在Java中使用iTextJAR打开PDF

1.Readthisarticleformoredetails.

2.

3.importjava.io.File;

4.importjava.io.FileOutputStream;

5.importjava.io.OutputStream;

6.importjava.util.Date;

7.

8.importcom.lowagie.text.Document;

9.importcom.lowagie.text.Paragraph;

10.importcom.lowagie.text.pdf.PdfWriter;

11.

12.publicclassGeneratePDF{

13.

14.publicstaticvoidmain(String[]args){

15.try{

16.OutputStreamfile=newFileOutputStream(newFile("C:

\\Test.pdf"));

17.

18.Documentdocument=newDocument();

19.PdfWriter.getInstance(document,file);

20.document.open();

21.document.add(newParagraph("HelloKiran"));

22.document.add(newParagraph(newDate().toString()));

23.

24.document.close();

25.file.close();

26.

27.}catch(Exceptione){

28.

29.e.printStackTrace();

30.}

31.}

32.}

复制代码

11.在Java上的HTTP代理设置 

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.JavaSingleton例子

1.Readthisarticleformore

2.details.

3.Update:

ThanksMarkusforthecomment.Ihaveupdatedthecodeand

4.changeditto

5.morerobustimplementation.

6.

7.

8.publicclassSimpleSingleton{

9.privatestaticSimpleSingletonsingleInstance=  newSimpleSingleton();

10.

11.//Markingdefaultconstructorprivate

12.//toavoiddirectinstantiation.

13.privateSimpleSingleton(){

14.}

15.

16.//GetinstanceforclassSimpleSingleton

17.publicstaticSimpleSingletongetInstance(){

18.

19.returnsingleInstance;

20.}

21.}

22.OnemoreimplementationofSingletonclass.ThankstoRalphandLukaszZielinski

23.

24.forpointingthisout.

25.

26.

27.publicenumSimpleSingleton{

28.INSTANCE;

29.publicvoiddoSomething(){

30.}

31.}

32.

33.//CallthemethodfromSingleton:

34.SimpleSingleton.INSTANCE.doSomething();

复制代码

13.在Java上做屏幕截图

1.Readthisarticleformoredetails.

2.

3.

4.importjava.awt.Dimension;

5.importjava.awt.Rectangle;

6.importjava.awt.Robot;

7.importjava.awt.Toolkit;

8.importjava.awt.image.BufferedImage;

9.importjavax.imageio.ImageIO;

10.importjava.io.File;

11.

12....

13.

14.publicvoidcaptureScreen(StringfileName)throwsException{

15.

16.DimensionscreenSize=Toolkit.getDefaultToolkit().getScreenSize();

17.RectanglescreenRectangle=newRectangle(screenSize);

18.Robotrobot=newRobot();

19.BufferedImageimage=robot.createScreenCapture(screenRectangle);

20.ImageIO.write(image,"png",newFile(fileName));

21.

22.}

23....

复制代码

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;

9.}

10.}

11.

12.//Itisalsopossibletofilterthelistofreturnedfiles.

13.//Thisexampledoesnotreturnanyfilesthatstartwith`.'.

14.FilenameFilterfilter=newFilenameFilter(){

15.publicbooleanaccept(Filedir,Stringname){

16.return!

name.startsWith(".");

17.}

18.};

19.children=dir.list(filter);

20.

21.//ThelistoffilescanalsoberetrievedasFileobjects

22.File[]files=dir.listFiles();

23.

24.//Thisfilteronlyreturnsdirectories

25.FileFilterfileFilter=newFileFilter(){

26.publicbooleanaccept(Filefile){

27.returnfile.isDirectory();

28.}

29.};

30.files=dir.listFiles(fileFilter);

复制代码

15.在Java中创建ZIP和JAR文件

1.importjava.util.zip.*;

2.importjava.io.*;

3.

4.publicclassZipIt{

5.publicstaticvoidmain(Stringargs[])throwsIOException{

6.if(args.length<2){

7.System.err.println("usage:

javaZipItZip.zipfile1file2file3");

8.System.exit(-1);

9.}

10.FilezipFile=newFile(args[0]);

11.if(zipFile.exists()){

12.System.err.println("Zipfilealreadyexists,pleasetryanother");

13.System.exit(-2);

14.}

15.FileOutputStreamfos=newFileOutputStream(zipFile);

16.ZipOutputStreamzos=newZipOutputStream(fos);

17.intbytesRead;

18.byte[]buffer=newbyte[1024];

19.CRC32crc=newCRC32();

20.for(inti=1,n=args.length;i

21.Stringname=args;

22.

展开阅读全文
相关资源
猜你喜欢
相关搜索
资源标签

当前位置:首页 > 初中教育 > 语文

copyright@ 2008-2023 冰点文库 网站版权所有

经营许可证编号:鄂ICP备19020893号-2