Common Java program fragments

Source: Internet
Author: User

1 , change the size of the array

Package Com.js.ai.modules.jsa.test;public class Testxf {private static object Resizearray (object oldarray, int newSize) { int oldsize=java.lang.reflect.array.getlength (Oldarray); 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;} public static void Main (string[] args) {int[] a = {-N-a};      A = (int[]) Resizearray (a,5);   A[3] = 4;       A[4] = 5;       for (int i=0; i<a.length; i++)          System.out.print (a[i]+ ";");}  }

2. sending HTTP requests for data generation

Package Com.js.ai.modules.jsa.test;import Java.io.bufferedreader;import Java.io.inputstreamreader;import Java.net.url;public class Testxf {public static void main (string[] args) {try {URL my_url=new url ("https://open.alipay.co M/platform/home.htm "); BufferedReader br=new BufferedReader (New InputStreamReader (My_url.openstream ())); String strtemp = "";   while (null!= (Strtemp=br.readline ())) {System.out.println (strtemp);}} catch (Exception e) {e.printstacktrace ();}}}

3. Send mail

Package Com.js.ai.modules.jsa.test;import Java.util.properties;import Javax.mail.message;import Javax.mail.messagingexception;import Javax.mail.session;import Javax.mail.transport;import Javax.mail.internet.internetaddress;import Javax.mail.internet.mimemessage;public class Testxf {public void PostMail  (String recipients[], string subject, String message, string from) throws Messagingexception {Boolean debug = false;//Set The host SMTP addressproperties props = new Properties ();p rops.put ("Mail.smtp.host", "smtp.example.com");//create some P Roperties and get the default sessionsession session = session.getdefaultinstance (props, null); Session.setdebug (Debug)  ;//Create a messagemessage msg = new MimeMessage (session);//Set the From and to addressinternetaddress 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 Email if you//Wantmsg.addheader ("Myheadername", "Myheadervalue");//Setting the Subject and Content Typemsg.setsubject (Subject ); msg.setcontent (Message, "Text/plain"); Transport.send (msg);}}

4. convert Array to Map

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

5. parsing/reading XML files

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> </stud ent> <student> <name>Simon</name> <grade>A</grade> &L    t;age>18</age> </student> </students> Java code: 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 {DOCUMENTB          Uilderfactory dbf = Documentbuilderfactory.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.getnodename ());                      NodeList studentlist = docele.getelementsbytagname ("student"); Print total student elements in document System.out. println ("Total stude                      NTS: "+ studentlist.getlength ()); if (studentlist! = null && studentlist.getlength () > 0) {for (int i = 0; i < student List.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)                                  . Getnodevalue ());                                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");  }    }

6, 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.startswith (".");      }      };        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 (Fil          E file) {return file.isdirectory ();      }      }; Files = diR.listfiles (FileFilter);  

7. Screen Capture program

Package Com.js.ai.modules.jsa.test;import Java.awt.dimension;import Java.awt.rectangle;import Java.awt.Robot; Import Java.awt.toolkit;import java.awt.image.bufferedimage;import java.io.file;import Javax.imageio.ImageIO; public class Testxf {public void Capturescreen (String fileName) throws Exception {         Dimension screensize = toolkit.getd Efaulttoolkit (). Getscreensize ();       Rectangle screenrectangle = new Rectangle (screensize);       Robot Robot = new Robot ();       BufferedImage image = Robot.createscreencapture (screenrectangle);       Imageio.write (Image, "PNG", New File (FileName));      } public static void Main (string[] args) throws Exception {testxf testxf =new testxf (); Testxf.capturescreen ("c:/users/ Administrator/desktop/jsaxfz/capturescreen.png ");}}

  

Common Java program fragments

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.