`

20个超级有用的Java程序片段(3)

    博客分类:
  • java
阅读更多

16. 解析/读取XML 文件

  Java代码

  1.  XML文件
  2.   <?xml version="1.0"?>
  3.   <students>
  4.   <student>
  5.   <name>John</name>
  6.   <grade>B</grade>
  7.   <age>12</age>
  8.   </student>
  9.   <student>
  10.   <name>Mary</name>
  11.   <grade>A</grade>
  12.   <age>11</age>
  13.   </student>
  14.   <student>
  15.   <name>Simon</name>
  16.   <grade>A</grade>
  17.   <age>18</age>
  18.   </student>
  19.   </students>
复制代码
Java代码
  1. package net.viralpatel.java.xmlparser;
  2.   import java.io.File;
  3.   import javax.xml.parsers.DocumentBuilder;
  4.   import javax.xml.parsers.DocumentBuilderFactory;
  5.   import org.w3c.dom.Document;
  6.   import org.w3c.dom.Element;
  7.   import org.w3c.dom.Node;
  8.   import org.w3c.dom.NodeList;
  9.   public class XMLParser {
  10.   public void getAllUserNames(String fileName) {
  11.   try {
  12.   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  13.   DocumentBuilder db = dbf.newDocumentBuilder();
  14.   File file = new File(fileName);
  15.   if (file.exists()) {
  16.   Document doc = db.parse(file);
  17.   Element docEle = doc.getDocumentElement();
  18.   // Print root element of the document
  19.   System.out.println("Root element of the document: "
  20.   + docEle.getNodeName());
  21.   NodeList studentList = docEle.getElementsByTagName("student");
  22.   // Print total student elements in document
  23.   System.out
  24.   .println("Total students: " + studentList.getLength());
  25.   if (studentList != null && studentList.getLength() > 0) {
  26.   for (int i = 0; i < studentList.getLength(); i++) {
  27.   Node node = studentList.item(i);
  28.   if (node.getNodeType() == Node.ELEMENT_NODE) {
  29.   System.out.println("=====================");
  30.   Element e = (Element) node;
  31.   NodeList nodeList = e.getElementsByTagName("name");
  32.   System.out.println("Name: "
  33.   + nodeList.item(0).getChildNodes().item(0)
  34.   .getNodeValue());
  35.   nodeList = e.getElementsByTagName("grade");
  36.   System.out.println("Grade: "
  37.   + nodeList.item(0).getChildNodes().item(0)
  38.   .getNodeValue());
  39.   nodeList = e.getElementsByTagName("age");
  40.   System.out.println("Age: "
  41.   + nodeList.item(0).getChildNodes().item(0)
  42.   .getNodeValue());
  43.   }
  44.   }
  45.   } else {
  46.   System.exit(1);
  47.   }
  48.   }
  49.   } catch (Exception e) {
  50.   System.out.println(e);
  51.   }
  52.   }
  53.   public static void main(String[] args) {
  54.   XMLParser parser = new XMLParser();
  55.   parser.getAllUserNames("c:\\test.xml");
  56.   }
  57.   }
复制代码
17. 把 Array 转换成 Map

  Java代码
  1.  import java.util.Map;
  2.   import org.apache.commons.lang.ArrayUtils;
  3.   public class Main {
  4.   public static void main(String[] args) {
  5.   String[][] countries = { { "United States", "New York" }, { "United Kingdom", "London" },
  6.   { "Netherland", "Amsterdam" }, { "Japan", "Tokyo" }, { "France", "Paris" } };
  7.   Map countryCapitals = ArrayUtils.toMap(countries);
  8.   System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));
  9.   System.out.println("Capital of France is " + countryCapitals.get("France"));
  10.   }
  11.   }
复制代码
18. 发送邮件

  Java代码
  1. import javax.mail.*;
  2.   import javax.mail.internet.*;
  3.   import java.util.*;
  4.   public void postMail( String recipients[ ], String subject, String message , String from) throws MessagingException
  5.   {
  6.   boolean debug = false;
  7.   //Set the host smtp address
  8.   Properties props = new Properties();
  9.   props.put("mail.smtp.host", "smtp.example.com");
  10.   // create some properties and get the default Session
  11.   Session session = Session.getDefaultInstance(props, null);
  12.   session.setDebug(debug);
  13.   // create a message
  14.   Message msg = new MimeMessage(session);
  15.   // set the from and to address
  16.   InternetAddress addressFrom = new InternetAddress(from);
  17.   msg.setFrom(addressFrom);
  18.   InternetAddress[] addressTo = new InternetAddress[recipients.length];
  19.   for (int i = 0; i < recipients.length; i++)
  20.   {
  21.   addressTo[i] = new InternetAddress(recipients[i]);
  22.   }
  23.   msg.setRecipients(Message.RecipientType.TO, addressTo);
  24.   // Optional : You can also set your custom headers in the Email if you Want
  25.   msg.addHeader("MyHeaderName", "myHeaderValue");
  26.   // Setting the Subject and Content Type
  27.   msg.setSubject(subject);
  28.   msg.setContent(message, "text/plain");
  29.   Transport.send(msg);
  30.   }
复制代码
19. 发送代数据的HTTP 请求

  Java代码
  1. import java.io.BufferedReader;
  2.   import java.io.InputStreamReader;
  3.   import java.net.URL;
  4.   public class Main {
  5.   public static void main(String[] args)  {
  6.   try {
  7.   URL my_url = new URL("http://coolshell.cn/");
  8.   BufferedReader br = new BufferedReader(new InputStreamReader(my_url.openStream()));
  9.   String strTemp = "";
  10.   while(null != (strTemp = br.readLine())){
  11.   System.out.println(strTemp);
  12.   }
  13.   } catch (Exception ex) {
  14.   ex.printStackTrace();
  15.   }
  16.   }
  17.   }
复制代码
20. 改变数组的大小

  Java代码

  查看源代码打印帮助
  1.  /**
  2.   * Reallocates an array with a new size, and copies the contents
  3.   * of the old array to the new array.
  4.   * @param oldArray  the old array, to be reallocated.
  5.   * @param newSize   the new array size.
  6.   * @return          A new array with the same contents.
  7.   */
  8.   private static Object resizeArray (Object oldArray, int newSize) {
  9.   int oldSize = java.lang.reflect.Array.getLength(oldArray);
  10.   Class elementType = oldArray.getClass().getComponentType();
  11.   Object newArray = java.lang.reflect.Array.newInstance(
  12.   elementType,newSize);
  13.   int preserveLength = Math.min(oldSize,newSize);
  14.   if (preserveLength > 0)
  15.   System.arraycopy (oldArray,0,newArray,0,preserveLength);
  16.   return newArray;
  17.   }
  18.   // Test routine for resizeArray().
  19.   public static void main (String[] args) {
  20.   int[] a = {1,2,3};
  21.   a = (int[])resizeArray(a,5);
  22.   a[3] = 4;
  23.   a[4] = 5;
  24.   for (int i=0; i<a.length; i++)
  25.   System.out.println (a[i]);
  26.   }
复制代码

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics