20个非常有用的JAVA程序片段.docx

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

20个非常有用的JAVA程序片段.docx

《20个非常有用的JAVA程序片段.docx》由会员分享,可在线阅读,更多相关《20个非常有用的JAVA程序片段.docx(21页珍藏版)》请在冰点文库上搜索。

20个非常有用的JAVA程序片段.docx

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

下面是20个非常有用的Java程序片段,希望能对你有用。

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

1.Stringa=String.valueOf

(2);//integertonumericstring

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

2.向文件末尾添加内容

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.得到当前方法的名字

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

4.转字符串到日期

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

或者是:

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

2.Datedate=format.parse(myString);

5.使用JDBC链接Oracle

1.publicclassOracleJdbcTest

2.{

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

4.

5.Connectioncon;

6.

7.publicvoidinit(FileInputStreamfs)throwsClassNotFoundException,SQLException,FileNotFoundException,IOException

8.{

9.Propertiesprops=newProperties();

10.props.load(fs);

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

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

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

14.Class.forName(driverClass);

15.

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

17.}

18.

19.publicvoidfetch()throwsSQLException,IOException

20.{

21.PreparedStatementps=con.prepareStatement("selectSYSDATEfromdual");

22.ResultSetrs=ps.executeQuery();

23.

24.while(rs.next())

25.{

26.//dothethingyoudo

27.}

28.rs.close();

29.ps.close();

30.}

31.

32.publicstaticvoidmain(String[]args)

33.{

34.OracleJdbcTesttest=newOracleJdbcTest();

35.test.init();

36.test.fetch();

37.}

38.}

6.把Javautil.Date转成sql.Date

1.java.util.DateutilDate=newjava.util.Date();

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

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

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.

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

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

12.longsize=inChannel.size();

13.longposition=0;

14.while(position

15.{

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

17.}

18.}

19.finally

20.{

21.if(inChannel!

=null)

22.{

23.inChannel.close();

24.}

25.if(outChannel!

=null)

26.{

27.outChannel.close();

28.}

29.}

30.}

8.创建图片的缩略图

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.

11.//determinethumbnailsizefromWIDTHandHEIGHT

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

13.intimageWidth=image.getWidth(null);

14.intimageHeight=image.getHeight(null);

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

16.if(thumbRatio

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

18.}else{

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

20.}

21.

22.//draworiginalimagetothumbnailimageobjectand

23.//scaleittothenewsizeon-the-fly

24.BufferedImagethumbImage=newBufferedImage(thumbWidth,thumbHeight,BufferedImage.TYPE_INT_RGB);

25.Graphics2Dgraphics2D=thumbImage.createGraphics();

26.graphics2D.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);

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

28.

29.//savethumbnailimagetooutFilename

30.BufferedOutputStreamout=newBufferedOutputStream(newFileOutputStream(outFilename));

31.JPEGImageEncoderencoder=JPEGCodec.createJPEGEncoder(out);

32.JPEGEncodeParamparam=encoder.getDefaultJPEGEncodeParam(thumbImage);

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

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

35.encoder.setJPEGEncodeParam(param);

36.encoder.encode(thumbImage);

37.out.close();

38.}

9.创建JSON格式的数据

请先阅读这篇文章了解一些细节,

并下面这个JAR文件:

json-rpc-1.0.jar(75kb)

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

阅读这篇文章了解更多细节

1.importjava.io.File;

2.importjava.io.FileOutputStream;

3.importjava.io.OutputStream;

4.importjava.util.Date;

5.

6.importcom.lowagie.text.Document;

7.importcom.lowagie.text.Paragraph;

8.importcom.lowagie.text.pdf.PdfWriter;

9.

10.publicclassGeneratePDF{

11.

12.publicstaticvoidmain(String[]args){

13.try{

14.OutputStreamfile=newFileOutputStream(newFile("C:

\\Test.pdf"));

15.

16.Documentdocument=newDocument();

17.PdfWriter.getInstance(document,file);

18.document.open();

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

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

21.

22.document.close();

23.file.close();

24.

25.}catch(Exceptione){

26.

27.e.printStackTrace();

28.}

29.}

30.}

11.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");

2.单实例Singleton示例

请先阅读这篇文章了解更多信息

1.publicclassSimpleSingleton{

2.privatestaticSimpleSingletonsingleInstance=newSimpleSingleton();

3.

4.//Markingdefaultconstructorprivate

5.//toavoiddirectinstantiation.

6.privateSimpleSingleton(){

7.}

8.

9.//GetinstanceforclassSimpleSingleton

10.publicstaticSimpleSingletongetInstance(){

11.

12.returnsingleInstance;

13.}

14.}

另一种实现

1.publicenumSimpleSingleton{

2.INSTANCE;

3.publicvoiddoSomething(){

4.}

5.}

6.

7.//CallthemethodfromSingleton:

8.SimpleSingleton.INSTANCE.doSomething();

13.抓屏程序

阅读这篇文章获得更多信息。

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....

10.

11.publicvoidcaptureScreen(StringfileName)throwsException{

12.

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

14.RectanglescreenRectangle=newRectangle(screenSize);

15.Robotrobot=newRobot();

16.BufferedImageimage=robot.createScreenCapture(screenRectangle);

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

18.

19.}

20....

14.列出文件和目录

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.

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.创建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[i];

22.Filefile=newFile(name);

23.if(!

file.exists()){

24.System.err.println("Skipping:

"+name);

25.continue;

26.}

27.BufferedInputStreambis=newBufferedInputStream(

28.newFileInputStream(file));

29.crc.reset();

30.while((bytesRead=bis.read(buffer))!

=-1){

31.crc.update(buffer,0,bytesRead);

32.}

33.bis.close();

34.//Resettobeginningofinputstream

35.bis=newBufferedInputStream(

36.new

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

当前位置:首页 > 表格模板 > 合同协议

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

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