下面是20个非常有用的Java程序片段,希望对你有用。内容比较早,可能有些功能已经过时了,但总体思路还是不错的,供参考。1.字符串有整数转换Stringa=String.valueOf(2);//integertonumericstringinti=Integer.parseInt(a);//numericstringtoanint2,在文件末尾添加内容BufferedWriterout=null;try{out=newBufferedWriter(newFileWriter("filename",true));out.write("aString");}catch(IOExceptione){//errorprocessingcode}finally{if(out!=null){out.close();}}3.获取当前方法名称StringmethodName=Thread.currentThread().getStackTrace()[1].getMethodName();4.将字符串转换为日期java.util.Date=java.text.DateFormat.getDateInstance().parse(dateString);或者:SimpleDateFormatformat=newSimpleDateFormat("dd.MM.yyyy");Datedate=format.parse(myString);5、使用JDBC链接Oracle6,将Javautil.Date转换为sql.Datejava.util.DateutilDate=newjava.util.Date();java.sql.DatesqlDate=newjava.sql.Date(utilDate.getTime());7.使用NIO进行快速文件复制8.创建图片缩略图9.创建JSON格式的数据,请先阅读这篇文章了解一些细节,以及以下JAR文件:json-rpc-1.0.jar(75kb)http://viralpatel.net/blogs/download/json/json-rpc-1.0.jarimportorg.json.JSONObject;......JSONObjectjson=newJSONObject();json.put("city","Mumbai");json.put("country","India");...Stringoutput=json.toString();...10.使用iTextJAR生成PDF阅读本文文章了解更多详情11.HTTP代理设置阅读本文了解更多详情System.getProperties().put("http.proxyHost","someProxyURL");System.getProperties().put("http.proxyPort","someProxyPort");System.getProperties().put("http.proxyUser","someUserName");System.getProperties().put("http.proxyPassword","somePassword");12.单实例Singleton示例请先阅读本文以获取更多信息//标记为defaultconstructorprivate//避免直接实例化.privateSimpleSingleton(){}//为classSimpleSingleton获取实例publicstaticSimpleSingletongetInstance(){returnssingleInstance;}}另一种实现publicenumSimpleSingleton{INSTANCE;publicvoiddoSomething(){}}//从Singleton调用方法:SimpleSingleton.Something();INSTANCE1.屏幕捕获程序阅读本文以获取更多信息。importjava.awt.Dimension;importjava.awt.Rectangle;importjava.awt.Robot;importjava.awt.Toolkit;importjava.awt.image.BufferedImage;importjavax.imageio.ImageIO;importjava.io.File;...publicvoidcaptureScreen(字符串文件名)throwsException{DimensionscreenSize=Toolkit.getDefaultToolkit().getScreenSize();RectanglescreenRectangle=newRectangle(screenSize);Robotrobot=newRobot();BufferedImageimage=robot.createScreenCapture(screenRectangle);ImageIO.write(图像,"png",newFile(文件名)));}...14、列出文件和目录15、创建ZIP和JAR文件importjava.util.zip.*;importjava.io.*;publicclassZipIt{publicstaticvoidmain(Stringargs[])throwsIOException{if(args.length<2){System.err.println("usage:javaZipItZip.zipfile1file2file3");System.exit(-1);}FilezipFile=newFile(args[0]);if(zipFile.exists()){System.err.println("Zipfilealreadyexists,pleasetryanother");System.exit(-2);}FileOutputStreamfos=newFileOutputStream(zipFile);ZipOutputStreamzos=newZipOutputStream(fos);intbytesRead;byte[]buffer=newbyte[1024];CRC32crc=newCRC32();for(inti=1,n=args.length;i
