1. The string has a integrated mutual conversion
String a = string.valueof (2); // Integer to Numeric String
int i = Integer.parseint (a); // Numeric String to An
2. Add content to the end of the file
BufferedWriter out = null; try {out = new bufferedWriter (New Filewriter ("" Filename, TRUE)); Out.Write ("Astring");} Catch (IOEXCEPTION E) Ror Processing Code} Finally {if (out ! = Null) {out.close ();}} 3. Get the name of the current method
String methodName = Thread.currentthRead (). GetStacktrace () [1] .GetMethodName ();
4. Transfer string to date
java.util.date = java.text.dateFormat.GetDateInstance (). PARSE (Date String);
Or:
SimpleDateFormat Format = New SimpleDateFormat ("dd.mm.yyyy");
Date date = format.parse (mystring);
5. Use JDBC link Oracle
Public class oraljdbctest {string driveclass = "oral.jdbc.driver.oderDriver"; connection con; Public void init (FileInputStream FS) Throws NotFoundexception, Sqlexception, FilenotFoundException, IOEXception {Properties Props = New Properties (); Props.load (fs) ; String url = props.getProperty ("db.url"); String username = props.GetProperty ("db.user"); string password = props.GetProperty ("db.passw Ord "); Class.Forname (DriverClass); Con = DriverManager.getConnection (url, username, password);} Public void fetch () Throws sqlexception, ioException {Preparedatement PS = Con.preparest ATEMENT ("Select Sysdate from Dual"); ResultSet RS = ps.executequry (); While rs.next ()) {// Do the things you do} RS.Close (); PS.Close ();} Public Static Void Main (String [] ARGS) ; test.init (); test.Fetch ();}} 6. Turn java util.date to sql.date
java.util.date Utildate = new java.util.date (); java.sql.date sqldate = new java.sql.date (utilDate.gettime ());
7. Use NIO to perform fast file copy
Public Static Void FileCopy (File In, File Out) Throws IOEXCEPTION {FileChannel Inchaannel = New FileInputStream (in) .getChannel (); FileChannel OutChannel = NEW F iLindputStream (out) .getChannel (); TRY {// infhannel.transferto (0, infhannel.size (), OutChannel); // Original - Apparently Has Trouble Copying Large Files On Windows // Magic Number for Windows, 64MB -32KB) Int maxcount = (64 * 1024 * 1024) - (32 * 1024); long size = infhannel.size (); long posity = 0; while (pose <size) {posity += Inchaannel.transferto (position, maxcount, outChannel);}}} FINAL. LY {if (infhannel! = Null) {infhannel.close ();} if (outChannel! = Null) {outChannel.close ();}}} 8. Create a thumbnail of pictures
Private Void CreateThumbnail (String Filename, Int Thumbwidth, Int Thumbheight, Int Quality, String Outfilename) Throws International Foundexception, IOEXCEPTION {// Load Image From Filename Image = Toolkit.getDefaultToolkit (). GetImage (FILENAME); Ker = NEW Mediaatracker (New Container ()); Mediaatracker.addimage (Image, 0); Mediaatracker.WaitForid (0); // Use this to test for errors at this point: system.out.pr. Intln (Mediaatracker.iserrory ()); / / Determine Thumbnail Size from Width and Height Double Thumbratio = (Double) ThumbWidth / (Double) Thumbheight; int ImageWidth = Image.getWidth (NU ll); int ImageHeight = Image.getheight (null); Double Imageratio = (Double) ImageWidth / ((Double) ImageWidth / ( Double) ImageHeight; if (Thumbratio <IMAGERATIO) {Thumbheight = (int) (thumbwidth / Imageratio);} Else {Thumbwidth = (int) (thumbheigh * i mageratio);} // Draw Original Image to Thumbnail Image Object and // Scale It to the new size on-the-Fly Buffredimage ThumbImage = New Buffredimage (ThumbwIdth, Thumbheight, BufferedImage.Type_INT_INT_RGB); Graphics2d = ThumbImage.creategraphics (); Graphics2d.setRenderinghint (renderinghints.key_interpolation, renderinghints.value_Interporation_bilinear) ; Graphics2d.drawimage (image, 0, 0, thumbWidth, thumbHeight, null); // save thumbnail image to outFilename BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(outFilename)); JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out); JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam (ThumbImage); Quality = math.max (0, math.min (quality, 100)); Param.SetQuality ((Float) Quality / 100.0F, FALSE); AM); Encoder.encode (thumbimage) ; out.Close ();}9. Create data in JSON format
And the jar file below: json-rpc-1.0.jar (75 kb) /http://t.cn/rz0bhua
Import org.json.jsonObject; ... ... jsonObject json = new jsonObject (); json.put ("city", "mumbai"); json.put ("country", "india"); ... String output = json.tostring (); ... 10. Use Itext jar to generate PDF
Import java.io.file; Import java.io.fileoutputStream; Import java.io.outputStream; Import Java.util.date; Import com.lowagie.text.document; Ort com.lowagie.text.paragraph; Import com. Lowagie .text.pdf.pdfwriter; Public Class Generatepdf {Public Static Void Main (String [] ARGS) {Try {OutputStream File = New FileoutStream (News ("C: // T eSt.pdf ")); (); Pdfwriter.getInstance (document, file); document.open (); Document.add (New Paragraph ("Hello Kiran"); ostring ()); document.close (); file.close ();} Catch (Exception E) {e.printstacktrace ();}}}}} 11. HTTP proxy settings
System.getProperties (). Put ("http.proxyhost", "SOMEPROXYURL"); System.getProperties (). Put ("http.proxyport", "SomeProxyPort"); system.getp roperties (). Put ("http.proxyuseer "," someUserName "); System.getProperties (). Put (" http.proxypassword "," somePassword "); 12. Single instance Singleton Example
Public Class Simplesingleton {Private Static Simpleongleton Singleinstance = New Simplesingleton (); // Marking Default Constructor Private // ION. Private Simplesingleton () {} // Get Instance for Class Simpleongleton Public Static Simpleton Getinstance () {Return Singleinstance; }} 13. Screening program
Import java.awt.dimension; Import Java.awt.Rectangle; Import Java.awt.ROBOT; Import java.Toolkit; Import Java.image.buffRedimage; I mport javax.imageio.imageio; Import java.io.file ... Public Void CaptureScreen (String Filename) Throws Exception {Dimension ScreenSize = Toolkit.getDefaultToolkit (). Rectangle = New RECTANGLE (ScreenSize); Robot Robot = New Robot (); BufferedImage Image = Robot.createScreenCapTure (ScreenRctangle); Imageio.Write (Image, "PNG", New File (FILENAME));} ... 14. List file and directory
File Dir = New File ("DirectoryName"); String [] Children = Dir.list (); if (Children == NULL) {// Either Dir Does Not Exist or is Not a Directory} (int i = 0; I <children.Length; I ++) {// get filename of file or directory string filename = children [i];} // It is all the list of restArnet F iles. // This exmple does not return Any Files that Start with `. '. Filenamefilter Filter = New Filenamefilter () {Public Boolean Accept (File Dir, String name) {Return! Name.startswith (". ") ;}}; Children = Dir.list (Filter) ; // The list of files can still be retrieved as file objects file [] files = dir.listFiles (); // This file only retarfilter filefilter = news. ieblic Boolean Accept (FILE FILE) {Return File .sdirectory ();}}; Files = Dir.listFiles (Filefilter); 15. Create zip and jar files
Import java.util.zip.*; Import Java.io.*; Public Class Zipit {Public Static void Main (String ARGS []) Throws IOEXCETION {if (ARGS.Length <2) {System.err.println ("usage : java ZipIt Zip.zip file1 file2 file3"); System.exit(-1); } File zipFile = new File(args[0]); if (zipFile.exists()) { System.err.println("Zip File Alream Exist, Please Try Another "); System.exit (-2);} FileoutPutStream FOS = New FileoutStream (Zipfile); ZipoutPutStream Zos = New utputstream (fos); Int bytesRead; byte [] buffer = new byte [1024] ; CRC32 CRC = New CRC32 (); For (int i = 1, n = args.length; i <n; i ++) {string name = args [i]; file file = new file (name); if (! File .exists ()) {system.errr.println ("Skipping:" + name); Continue;} BuffreDInputStream BIS = New bufferedInputStream (New FileInputStream); CRC.Resee t (); ((bytesream = bis.read (buffer)! = -1) {CRC.UPDATE (buffer, 0, bytesRead);} bis.close (); // reset to beginning of input stream bis = new buffered am (file); Zipentry Entry = New Zipentry (name); entry.setMethod (zipentry.stored); entry.setcompressetsize (file.length ()); ETCRC (CRC.GetValue ()); ZOS .putnextERY (Entry); While (bytesRead = bis.read (buffer)! = -1) {zos.write (buffer, 0, bytesread);} bis.close ();} zos.close ();} }16. Analyze/read xml file
XML file
<? xml version = "1.0"?> <students> <student> <name> John </name> <Grade> B </Grade> <Age> 12 </Age> </STUDENT> <Name> <Name> Mary </name> <Grade> A </Grade> <Age> 11 </Age> </STUDENT> <student> <Name> Simon </name> <Grade> A </Grade> <EGE> 18 </</ Age> </Student> </STUDENTS>
Java code
<span style = "font-family: arial; font-size: 14px;"> package network. ENTBUILDER; Import Javax.xml.parsers .DocumentbuilderFactory; Import org.W3C.Document; Import org.W3C.DOM.Element; Import org.W3C.De; Import Org.w3c.duDelist; Public Ass XMLPARSER {Public Void GetalluserNames (String Filename) {TRY {DocumentBuilderFactory dbf = documentbuilderFactory.newinstance (); DocumentBuilder db = dbf.newdocumentbuilder (); me); if (file.exist ()) {document doc = db.parse (file); Element DOCELE = DOC.GetDocumentedLement (); // Print Root Element of the Document System.out.println ("Root Element of the Document:" + DOCETNODNAME ()); ELIST StudentList = DOCELE.Getelements Bytagname ("Student"); // Print Total Student Elements in Document System.out .println ("Total Students:" + StudentList.getLength ()); if (StudentList! = NULL && StuderList.get.get.get. Length ()> 0) {for (int i = 0; i <studentList.getlength (); I ++) {node node = statentList.item (i); if (node.getNodeType () == node.element_node) {sysem.outln ("==== ==== =============== "); Element e = (Element) node; nodelist nodelist = e.GetelementsBytagName (" name "); System.out.println (" name: " + nodelist.itmm (0) .GetChildNodes (). Item (0) .getNodeValue ()); nodelist = e.GetelementsBytagname ("Grade"); System.out.println ("Grade:" + Nodelist.Item (0 ) .getchildNodes () .Item (0) .getNodeValue ()); nodelist = e.GetelementsBytagname ("Age"); System.out.println ("Age:" + Nodelist.Item (0) .GetChildNodes (). Item (). Item 0) .getNodeValue ();}}} Else {System.exit (1);}} Catch (Exception E) {System.out.println (E);} Public Static void Main (String [] ARGS) {xmlparser er = New xmlparser (); Parser.getalluserNames ("" c: //test.xml ");}} 17. Convert array to map
Import java.util.map; Import org.apache.lang.arrayutils; Public Class Main {Public Static void Main (string [] args) {string [] [] Countries. = {"United states", "New York "}, {" United Kingdom "," London "}, {" Netherland "," Amsterdam "}, {" JAPAN "," Tokyo "}, {" frame "," Paris "}; ILS. Tomap (Countries); System.out.println ("Capital of JAPAN is" + CountryCapitals.get ("JAPAN"); System.out.println ("Capital of France is" + Count " Trycapitals.get ("France")) ;}} 18. Send mail
Import javax.mail.*; Import javax.mail.internet.*; Import java.util.*; Public void postmail (String recipients [], String Subject, String GE, String from) Throws MessagingException {Boolean Debug = false; / /Set the host SMTP Address Properties Props = New Properties (); PROPS.Put ("MAIL.SMTP.HOST", "SMTP.Example.com"); default session session session = session. GetDefaultInstance (props, null); session.setdebug (debug); // Create a message message msg = New MimeMessage (session); // s internetAddress addressfrom = new Internetaddress (from); msg.setfrom (addressfrom ).; dress (recipients [i]);} msg.setRcipients ( Message.Recipienttype.to, Addressto); // Optional: You can also set your custom headers in the email if you want msg.addheader ("MyHeaderName", "myhead Ervalue "); // setting the subject and content type msg.setsubject (Subject); msg.setContent (message, "text/plain"); transport.Send (msg);} 19. HTTP request sending proxy data
Import java.io.BuffRedReader; Import Java.Io.InputStreamReader; Import Java.net.url; Public Class Main {Public Static void Main (String [] ARGS) {Try {Url my_url = new url ("http: // coolshell .cn/"); bufferedReader br = new bufferedReader ()) {System.out.println (StRTEMP);}} Catch (Exception EX) {ex.printstacktrace ();}}} 20. Change the size of the array
/** * Reallocats an array with a new size, and Copies the Contents * of the Old Array to the New Array. * @Param Oldarray the Old Array, . * @param newsize the new array size. * @Return A new array with the ame contents. */Private Static Object Resizearray (Object Oldarray, Int Newsize) {int Oldsize = java.lang.reflet.GetLengtLengt h (Oldarray); Class Elementtype = Oldarray.getClass (). GetComponenttype () ; Object newarray = java.lang.reflect.array.newinstance (ElementType, Newsize); int PreserVelenth = math.min (OLDSIZE, Newsize); IF (PRESERVEENGTH> 0) Sy. STEM.ARAYCOPY (Oldarray, 0, Newarray, 0, PreserVEENGTH ); RETURN NEWARAY;} // Test Routine for Resizearray (). Public Static void Main (string [] art) {int [] a = {1,2,3}; 5); a [3] = 4; a [4] = 5; for (int i = 0; I <a.Length; i ++) System.out.println (a [i]);}The above is all the contents of this article. I hope everyone can like it.