[java]代码库
import java.util.zip.*;import java.io.*;
John B 12 Mary A 11 Simon A 18
JohnB12MaryA11SimonA18Java code to parse above XML.
package net.viralpatel.java.xmlparser;
importjava.io.File;importjavax.xml.parsers.DocumentBuilder;importjavax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;importorg.w3c.dom.Element;importorg.w3c.dom.Node;importorg.w3c.dom.NodeList;
public class XMLParser
public void getAllUserNames(String fileName)tryDocumentBuilderFactory dbf =
// Print root element of thedocumentSystem.out.println("Rootelement of the document: "+docEle.getNodeName());
NodeList studentList = docEle.getElementsByTagName
("student");
// Print total student elementsindocumentSystem.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)
.getNodeValue());
nodeList =
e.getElementsByTagName("age");System.out.println("Age: "+
nodeList.item(0).getChildNodes().item(0)
.getNodeValue()); else System.exit(1); catch (Exceptione)System.out.println(e);public static void main(String args)
XMLParser parser =newXMLParser();parser.getAllUserNames("c:\\test.xml");17.ConvertArray to Map in Java
import java.util.Map; importorg.apache.commons.lang.ArrayUtils;public class Main public staticvoid main(String args) Stringcountries = "United States", "NewYork" , "United Kingdom",
"London" , "Netherland", "Amsterdam" , "Japan", "Tokyo","France", "Paris"
; Map countryCapitals =ArrayUtils.toMap(countries);System.out.println("Capital of Japan is" +countryCapitals.get("Japan")); System.out.println("CapitalofFrance is " + countryCapitals.get("France"));
importjava.util.Map;importorg.apache.commons.lang.ArrayUtils;
public class Main
public static void main(String args) String countries ="UnitedStates", "New York" , "United Kingdom",
"London" , "Netherland", "Amsterdam" , "Japan", "Tokyo","France", "Paris"
;
Map countryCapitals = ArrayUtils.toMap(countries);
System.out.println("Capital of Japan is "+countryCapitals.get("Japan"));System.out.println("Capital ofFranceis " + countryCapitals.get("France"));18. Send Email usingJava
import javax.mail.*; import javax.mail.internet.*;importjava.util.*; public void postMail( String recipients[ ],Stringsubject, String message , String
from) throws MessagingException boolean debug = false; //Setthehost smtp address Properties props = newProperties();props.put("mail.smtp.host", "smtp.example.com"); //create someproperties and get the default Session Session session=Session.getDefaultInstance(props, null);session.setDebug(debug);// create a message Message msg = newMimeMessage(session); // setthe from and to address InternetAddressaddressFrom = newInternetAddress(from); msg.setFrom(addressFrom);InternetAddressaddressTo = new InternetAddress[recipients.length];for (int i = 0;i < recipients.length; i++) addressTo[i] =newInternetAddress(recipients[i]);msg.setRecipients(Message.RecipientType.TO,addressTo); // Optional: You can also set your custom headers inthe Email if you Wantmsg.addHeader("MyHeaderName","myHeaderValue"); // Setting theSubject and Content Typemsg.setSubject(subject);msg.setContent(message, "text/plain");Transport.send(msg);
import javax.mail.*;importjavax.mail.internet.*;importjava.util.*;
public void postMail( String recipients[ ], String subject,Stringmessage , String
from) throws MessagingExceptionboolean debug = false;
//Set the host smtp addressProperties props =newProperties();props.put("mail.smtp.host","smtp.example.com");
// create some properties and get the defaultSessionSessionsession =Session.getDefaultInstance(props,null);session.setDebug(debug);
// create a messageMessage msg = new MimeMessage(session);
// set the from and to addressInternetAddress addressFrom =newInternetAddress(from);msg.setFrom(addressFrom);
InternetAddress addressTo =newInternetAddress[recipients.length];for (int i = 0; i<recipients.length; i++)addressTo[i] =newInternetAddress(recipients[i]);msg.setRecipients(Message.RecipientType.TO,addressTo);
// Optional : You can also set your custom headers in the Emailifyou Wantmsg.addHeader("MyHeaderName", "myHeaderValue");
// Setting the Subject andContentTypemsg.setSubject(subject);msg.setContent(message,"text/plain");Transport.send(msg);19.Send HTTP request &fetching data using Java
import java.io.BufferedReader; importjava.io.InputStreamReader;import java.net.URL; public class Mainpublic static voidmain(String args) try URL my_url =newURL("http://www.viralpatel.net/blogs/"); BufferedReader br =newBufferedReader(new InputStreamReader
importjava.io.BufferedReader;importjava.io.InputStreamReader;importjava.net.URL;
public class Main public static void main(String args) tryURLmy_url = newURL("http://www.viralpatel.net/blogs/");BufferedReaderbr = newBufferedReader(new
/** * Reallocates an array with a new size, and copiesthecontents * of the old array to the new array. * @m oldArray theoldarray, to be reallocated. * @m newSize the new array size.*@returnA new array with the same contents. */ private statictresizeArray (t oldArray, int newSize) int oldSize=java.lang.reflect.Array.getLength(oldArray); Class elementType=oldArray.getClass().getComponentType(); t newArray=java.lang.reflect.Array.newInstance( elementType,newSize);intpreserveLength = Math.min(oldSize,newSize); if (preserveLength>0) System.arraycopy (oldArray,0,newArray,0,preserveLength);returnnewArray; // Test routine for resizeArray(). public staticvoidmain (String args) int a = 1,2,3; a = (int)resizeArray(a,5);a3= 4;a4= 5; for (int i=0; i System.out.println (a[i]);