Common code for Java development

Source: Internet
Author: User

1. Strings have integer conversions to each other

String a = string.valueof (2);   Integer to numeric string  int i = Integer.parseint (a);//numeric string to an int

  

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) {  //Error processing code} finally {  if (out! = null) {    out.close ();  }}

  

3. Get the name of the current method

String methodName = Thread.CurrentThread (). Getstacktrace () [1].getmethodname ();

  

4. Turn 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. Using JDBC to link Oracle

public class oraclejdbctest{String driverclass = "     Oracle.jdbc.driver.OracleDriver ";     Connection con;    public void init (FileInputStream fs) throws ClassNotFoundException, 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.password");       Class.forName (Driverclass);  Con=drivermanager.getconnection (URL, userName, password); } public void Fetch () throws SQLException, IOException {preparedstatement PS = con.preparestatement ("Select SYSDA    TE from dual ");       ResultSet rs = Ps.executequery ();    while (Rs.next ()) {//Does the thing you do} rs.close ();  Ps.close ();    } public static void Main (string[] args) {oraclejdbctest test = new Oraclejdbctest ();    Test.init ();  Test.fetch (); }}

  

6. Util Java. Date turns into SQL. Date

Java.util.Date utildate = new Java.util.Date () java.sql.Date sqldate = new Java.sql.Date (Utildate.gettime ());

  

7. Fast file copy using NiO

public static void FileCopy (file-in, file-out)      throws IOException  {    FileChannel inchannel = new Fileinputstr EAM (in). Getchannel ();    FileChannel Outchannel = new FileOutputStream (out). Getchannel ();    Try    {//     Inchannel.transferto (0, Inchannel.size (), outchannel);   Original--apparently have trouble copying large files on Windows          //magic number for Windows, 64MB-32KB)      int MaxCount = (* * 1024x768)-(* 1024x768);      Long size = Inchannel.size ();      Long position = 0;      while (position < size)      {        position + = Inchannel.transferto (position, MaxCount, Outchannel);      }    }    finally    {      if (inchannel! = null)      {        inchannel.close ();      }      if (Outchannel! = null)      {        outchannel.close ();}}  }

  

8. Create a thumbnail image of a picture

private void Createthumbnail (string filename, int thumbwidth, int thumbheight, int quality, string outfilename) throws Interruptedexception, FileNotFoundException, IOException {//load image from filename image image = Toolkit.getdef    Aulttoolkit (). getImage (filename);    Mediatracker mediatracker = new Mediatracker (new Container ());    Mediatracker.addimage (image, 0);    Mediatracker.waitforid (0);       Use the this to test for errors in this point:System.out.println (Mediatracker.iserrorany ());    Determine thumbnail size from WIDTH and HEIGHT double thumbratio = (double) thumbwidth/(double) thumbheight;    int imagewidth = Image.getwidth (null);    int imageheight = Image.getheight (null);    Double imageratio = (double) imagewidth/(double) imageheight;    if (Thumbratio < imageratio) {thumbheight = (int) (thumbwidth/imageratio);    } else {thumbwidth = (int) (thumbheight * imageratio); }//Draw original image to thumbnail image object and//sCale it to the new size on-the-fly bufferedimage thumbimage = new BufferedImage (Thumbwidth, Thumbheight, BufferedImage.    TYPE_INT_RGB);    Graphics2D graphics2d = Thumbimage.creategraphics ();     Graphics2d.setrenderinghint (Renderinghints.key_interpolation, renderinghints.value_interpolation_bilinear);       Graphics2d.drawimage (image, 0, 0, thumbwidth, thumbheight, NULL); Save thumbnail image to outfilename bufferedoutputstream out = new Bufferedoutputstream (New FileOutputStream (outFile    name));    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);    Encoder.setjpegencodeparam (param);    Encoder.encode (Thumbimage);  Out.close (); }

  

9. Create JSON-formatted data

And the following jar file: Json-rpc-1.0.jar (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. Generate PDF using Itext jar

Import Java.io.file;import java.io.fileoutputstream;import java.io.outputstream;import java.util.Date;   Import Com.lowagie.text.document;import com.lowagie.text.paragraph;import com.lowagie.text.pdf.PdfWriter;   public class Generatepdf {public     static void Main (string[] args) {    try {      outputstream file = new FILEOUTPUTST Ream (New File ("C:\\test.pdf"));          Document document = new document ();      Pdfwriter.getinstance (document, file);      Document.open ();      Document.add (New Paragraph ("Hello Kiran"));      Document.add (New Paragraph () (New Date (). toString ()));         Document.close ();      File.close ();       } catch (Exception e) {         e.printstacktrace ();}}  }

  

HTTP proxy Settings

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. Single Instance Singleton example

public class Simplesingleton {  private static Simplesingleton singleinstance = new Simplesingleton ();      Marking default constructor Private  //to Avoid direct instantiation.  Private Simplesingleton () {  }     //get instance for class Simplesingleton public  static Simplesingleton GetInstance () {       return singleinstance;  }}

  

13. Screen Capture Program

Import Java.awt.dimension;import java.awt.rectangle;import Java.awt.robot;import Java.awt.toolkit;import Java.awt.image.bufferedimage;import Javax.imageio.imageio;import Java.io.File;   ...   public void Capturescreen (String fileName) throws Exception {     Dimension screensize = Toolkit.getdefaulttoolkit (). Getscreensize ();   Rectangle screenrectangle = new Rectangle (screensize);  Robot Robot = new Robot ();  BufferedImage image = Robot.createscreencapture (screenrectangle);  Imageio.write (Image, "PNG", New File (FileName));   } ...

  

14. list Files and directories

File dir = new file ("DirectoryName"); String[] Children = dir.list (); if (children = = null) {   //either dir does not exist or was not a directory} else {for   (int i=0; I < children. Length i++) {     //Get filename of file or directory     String filename = children[i];}   }    It is also possible to filter the list of returned files. This example does no return any files that start with '. '.  FilenameFilter filter = new FilenameFilter () {public   Boolean accept (File dir, String name) {     return!NAME.STARTSW ITH (".");   } }; Children = dir.list (filter);    The list of files can also be retrieved as File objects file[] files = dir.listfiles ();    This filter is returns directories FileFilter FileFilter = new FileFilter () {public   Boolean accept (file file) {     return File.isdirectory ();   } }; Files = dir.listfiles (FileFilter);

  

15. Creating Zip and Jar files

Import Java.util.zip.*;import java.io.*; public class Zipit {public static void main (String args[]) throws IOException {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 already exists, please try another");    System.exit (-2);    } fileoutputstream fos = new FileOutputStream (ZipFile);    Zipoutputstream Zos = new Zipoutputstream (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.err.println ("skipping:" + name);      Continue      } Bufferedinputstream bis = new Bufferedinputstream (new FileInputStream (file));      Crc.reset (); while ((bytesread = bis.read (buffer))! =-1) {Crc.update (BuffeR, 0, Bytesread);      } bis.close ();      Reset to beginning of input stream bis = new Bufferedinputstream (new FileInputStream (file));      ZipEntry entry = new ZipEntry (name);      Entry.setmethod (zipentry.stored);      Entry.setcompressedsize (File.length ());      Entry.setsize (File.length ());      ENTRY.SETCRC (Crc.getvalue ());      Zos.putnextentry (entry);      while ((bytesread = bis.read (buffer))! =-1) {zos.write (buffer, 0, bytesread);    } bis.close ();  } zos.close (); }}

  

16. Parsing/reading an XML file

XML file

<?xml version= "1.0"?><students>  <student>    <name>John</name>    <grade >B</grade>    <age>12</age>  </student>  <student>    <name> mary</name>    <grade>A</grade>    <age>11</age>  </student>  <student>    <name>Simon</name>    <grade>A</grade>    <age>18</ Age>  </student></students>

  

Java code

<span style= "FONT-FAMILY:ARIAL;FONT-SIZE:14PX;"    >package Net.viralpatel.java.xmlparser;   Import Java.io.file;import Javax.xml.parsers.documentbuilder;import javax.xml.parsers.DocumentBuilderFactory;   Import Org.w3c.dom.document;import org.w3c.dom.element;import org.w3c.dom.node;import org.w3c.dom.NodeList; public class Xmlparser {public void Getallusernames (String fileName) {try {documentbuilderfactory dbf = Doc      Umentbuilderfactory.newinstance ();      Documentbuilder db = Dbf.newdocumentbuilder ();      File File = new file (fileName);        if (file.exists ()) {Document doc = db.parse (file);           Element Docele = Doc.getdocumentelement (); Print root element of the document SYSTEM.OUT.PRINTLN ("root element of the document:" + Docele.getno           Dename ());           NodeList studentlist = docele.getelementsbytagname ("student"); Print total student elements in document System.out. println ("Total studentS: "+ studentlist.getlength ()); if (studentlist! = null && studentlist.getlength () > 0) {for (int i = 0; i < studentlist.getlength ();               i++) {Node node = Studentlist.item (i); if (node.getnodetype () = = Node.element_node) {System.out. println ("=====================                 ");              Element e = (element) node;              NodeList NodeList = e.getelementsbytagname ("name"); System.out.println ("Name:" + nodelist.item (0). Getchildnodes (). Item (0). Getnodevalue                 ());              NodeList = E.getelementsbytagname ("Grade"); System.out.println ("Grade:" + nodelist.item (0). Getchildnodes (). Item (0). Getnodevalu                 E ());              NodeList = E.getelementsbytagname ("Age"); System.out.println ("Age:" + nodelist.item (0). Getchildnodes (). Item (0). GetNodeValue ());        }}} else {system.exit (1);    }}} catch (Exception e) {System.out.println (e);    }} public static void Main (string[] args) {xmlparser parser = new Xmlparser ();  Parser.getallusernames ("C:\\test.xml"); }}

  

17. Convert Array to Map

Import Java.util.map;import org.apache.commons.lang.ArrayUtils;   public class Main {public    static void Main (string[] args) {  string[][] countries = {"states", "New York "}, {" Kingdom "," London "},     {" Netherland "," Amsterdam "}, {" Japan "," Tokyo "}, {" France "," Paris "}};
   
    map countrycapitals = arrayutils.tomap (countries);     System.out.println ("Capital of Japan" + countrycapitals.get ("Japan"));  System.out.println ("Capital of France is" + countrycapitals.get ("France"));}}
   

  

18. Send Mail

Import Javax.mail.*;import Javax.mail.internet.*;import java.util.*; public void Postmail (string recipients[], string subject, String message, string from) throws Messagingexception {Boo      Lean debug = false;   Set the host SMTP address Properties props = new Properties ();     Props.put ("Mail.smtp.host", "smtp.example.com");  Create some properties and get the default session session = Session.getdefaultinstance (props, null);     Session.setdebug (Debug);     Create a message message msg = new MimeMessage (session);  Set the From and to address internetaddress Addressfrom = new internetaddress (from);     Msg.setfrom (Addressfrom);  internetaddress[] Addressto = new Internetaddress[recipients.length];  for (int i = 0; i < recipients.length; i++) {Addressto[i] = new internetaddress (recipients[i]);     } msg.setrecipients (Message.RecipientType.TO, Addressto); Optional:you can also set your custom headers in the e-mail if you want Msg.addheader ("Myheadername "," Myheadervalue ");  Setting the Subject and Content Type msg.setsubject (Subject);  Msg.setcontent (Message, "Text/plain"); Transport.send (msg);}

  

19. HTTP request to send generation data

Import Java.io.bufferedreader;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 (New InputStreamReader (My_url.openstream ()));       String strtemp = "";      while (null! = (strtemp = Br.readline ())) {      System.out.println (strtemp);    }    } catch (Exception ex) {      Ex.printstacktrace ();}}}  

  

20. Changing the size of the array

/*** reallocates An array with a new size, and copies the contents* of the old array to the new array.* @param oldarray th e old array, to is reallocated.* @param newSize the  new array size.* @return     A new array with the same contents.*/ Private static Object Resizearray (object oldarray, int newSize) {   int oldsize = java.lang.reflect.Array.getLength (ol Darray);  Class ElementType = Oldarray.getclass (). Getcomponenttype ();  Object NewArray = java.lang.reflect.Array.newInstance (     elementtype,newsize);  int preservelength = Math.min (oldsize,newsize);  if (Preservelength > 0)   system.arraycopy (oldarray,0,newarray,0,preservelength);  return newarray;}   Test routine for Resizearray (). public static void Main (string[] args) {  int[] a = {};  A = (int[]) Resizearray (a,5);  A[3] = 4;  A[4] = 5;  for (int i=0; i<a.length; i++)   System.out.println (A[i]);}

  

21. Iterate through all the parameters and values passed over the page

Enumeration<?> en = Request.getparameternames ();        while (En.hasmoreelements ()) {            String el = en.nextelement (). toString ();          System.out.println ("| | | | |" +el+ "=" +request.getparameter (EL));        

  

JSON resolves to list

/** * JSON parsing * @param jsonstring * @return * @throws jsonexception */public list<datavo> jsontest (String jsonstring) Throws Jsonexception{//string jsonstring= "{\" answers\ ": [{\" loginname\ ": \" zhangfan\ ", \" password\ ": \" Userpass\ "},{ \ "password\": \ "Userpass\", \ "email\": \ "[Email protected]\"}]} "; Jsonobject json= New Jsonobject (jsonstring); Jsonarray Jsonarray=json.getjsonarray ("ARR"); list<datavo> answerlist = new arraylist<datavo> (); for (int i=0;i<jsonarray.length (); i++) {JSONObject Relue= (jsonobject) jsonarray.get (i); Long id= (long) relue.get ("id"); String val = (string) relue.get ("Val");D atavo datavo = new Datavo ();d Atavo.setid (ID);d Atavo.setval (val); Answerlist.add (Datavo);} return answerlist;}

  

  

Common code for Java development

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.