Java核心代码例程
1.Java核心代码例程之:HelloWorld.java
// The most basic Java program
public class HelloWorld
{
public static void main(String args[]) throws Exception
{
System.out.println("Hello World!");
}
}
2. Java核心代码例程之:StringBufferDemo.java
/ **
* Demo use of a StringBuffer
***/
public class StringBufferDemo
{
public static void main(String args[]) throws Exception
{
StringBuffer sb = new StringBuffer();
sb.append("Hello, World!
");
sb.append(123);
sb.append(", ");
sb.append(2.5);
System.out.println(sb.toString());
}
}
3. Java核心代码例程之:DateFormat.java
import java.text.*;
/**
* Demo date formatting.
***/
public class DateFormat
{
public static void main(String args[]) throws Exception
{
SimpleDateFormat sdf = new SimpleDateFormat("MM.dd.yy kk.mm.ss.S");
System.out.println(sdf.format(new java.util.Date()));
}
}
4. Java核心代码例程之:VectorDemo.java
import java.util.*;
/**
* Demonstrates how to use a Vector (essentially a growable array).
***/
public class VectorDemo
{
public static void main(String args[]) throws Exception
{
Vector v = new Vector();
v.addElement("Mary");
v.addElement("John");
v.addElement("David");
v.addElement("Pam");
v.addElement("Joe");
for (int i=0; i < v.size(); i++)
System.out.println("Hello " + (String)v.elementAt(i));
}
}
5. Java核心代码例程之:JDBC.java
import java.sql.*;
/**
* Simple demo of how to perform a SQL query using JDBC.
**/
public class JDBC
{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:EmpPrjDB", "admin", "letmein");
Statement stmt = conn.createStatement();
ResultSet rslt = stmt.executeQuery("SELECT name, city FROM employee");
while (rslt.next())
{
System.out.println("Hello World from "
+ rslt.getString(1) // You can use getString(columnNumber)
+ " in "
+ rslt.getString("city")); // Or, you can use getString(columnName)
}
rslt.close();
stmt.close();
conn.close();
}
}
6. Java核心代码例程之:RMIExampleServer.java
import java.rmi.*;
import java.rmi.server.*;
/**
* This class is a simple example of a RMI Server
* @author Renga
**/
public class RMIExampleServer extends UnicastRemoteObject
implements RMIExample {
/**
* Do nothing constructor
* @throws RemoteException
**/
public RMIExampleServer() throws RemoteException {
System.out.println( "RMIExampleServer::cntr" );
}
/**
* Returns "Hello World from RMI!"
* @return A string
* @throws RemoteException
**/
public String sayHello() throws RemoteException {
return "Hello World from RMI!";
}
}
7. Java核心代码例程之:CalendarDemo.java
import java.util.*;
/**
* Demo Calendar class.
***/
public class CalendarDemo
{
public static void main(String args[]) throws Exception
{
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(new Date());
System.out.println((cal.get(Calendar.MONTH)+1) + "/" +
cal.get(Calendar.DAY_OF_MONTH) + "/" +
cal.get(Calendar.YEAR));
}
}
8. Java核心代码例程之:PropertiesDemo.java
import java.util.*;
import java.io.*;
/**
* Demonstrates how to sort strings.
***/
public class PropertiesDemo
{
public static void main(String args[]) throws Exception
{
Properties props = new Properties();
props.put("db.user", "jack");
props.put("db.password", "opendoor");
// getProperty will return the value if found, otherwise null
System.out.println(props.getProperty("db.user"));
// getProperty will return the value if found, otherwise "none"
System.out.println(props.getProperty("db.password", "none"));
/*
// You can also load properties from a file
FileInputStream fis = new FileInputStream("my.properties");
props.load(fis);
fis.close();
**/
}
}
9. Java核心代码例程之:ThreadDemo.java
/**
* Demo how threads in Java work
***/
public class ThreadDemo
extends Thread
{
private int startingNumber=0;
public ThreadDemo(int startingNumber)
{
this.startingNumber=startingNumber;
}
// this method runs in a separate thread
public void run()
{
//loop 10 times
for (int i=startingNumber; i < (startingNumber+100); i++)
System.out.println(i);
}
// test driver
public static void main(String args[]) throws Exception
{
ThreadDemo t1=new ThreadDemo(100),
t2=new ThreadDemo(200);
t1.start();
t2.start();
}
}
10. Java核心代码例程之:RMIExampleSetup.java
import java.rmi.*;
import javax.naming.*;
/**
* This class registers RMIExampleServer with the RMI registry
* @author Renga
**/
public class RMIExampleSetup {
/**
* Main method
* @param args Command-line arguments
**/
public static void main( String[] args ) {
try {
// Set the security manager
System.setSecurityManager( new RMISecurityManager() );
// Create a new object of RMIExampleServer
RMIExampleServer server = new RMIExampleServer();
// Bind this object with the RMI registry
Naming.bind( "RMIExample", server );
} catch( Exception e ) {
e.printStackTrace();
}
}
}
11. Java核心代码例程之:RMIExample.java
import java.rmi.*;
/**
* Remote interface for the RMIExampleServer
* @author Renga
**/
public interface RMIExample extends Remote {
/**
* Returns a string to the caller
* @return A string
* @throws RemoteException
**/
public String sayHello() throws RemoteException;
}
12. Java核心代码例程之:java.policy
grant {
permission java.security.AllPermission;
};
13. Java核心代码例程之:ShowFileContent.java
import java.io.*;
// Read a file using BufferedReader.readLine()
public class ShowFileContent
{
public static void main(String args[]) throws Exception
{
FileReader fr = new FileReader("c:/autoexec.bat");
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null)
System.out.println(line);
br.close();
}
}
14. Java核心代码例程之:JavaMail ----PopMail.java
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
/**
* Demonstrate POP mail using JavaMail. Requires mail.jar activation.jar
* Sample run: java -cp .;mail.jar;activation.jar PopMail
**/
public class PopMail
{
public static void main(String args[]) throws Exception
{
String pop3Host="myhost.com", popUser="john", popPassword="letmein";
Session session = Session.getDefaultInstance(System.getProperties(), null);
Store store = session.getStore("pop3");
store.connect(pop3Host, -1, popUser, popPassword);
// Open the default folder
Folder folder = store.getDefaultFolder();
if (folder == null)
throw new NullPointerException("No default mail folder");
folder = folder.getFolder("INBOX");
if (folder == null)
throw new NullPointerException("Unable to get folder: " + folder);
// Get message count
folder.open(Folder.READ_WRITE);
int totalMessages = folder.getMessageCount();
if (totalMessages == 0)
{
System.out.println("No messages found in inbox");
folder.close(false);
store.close();
return;
}
// Get attributes & flags for all messages
Message[] messages = folder.getMessages();
FetchProfile fp = new FetchProfile();
fp.add(FetchProfile.Item.ENVELOPE);
fp.add(FetchProfile.Item.FLAGS);
fp.add("X-Mailer");
folder.fetch(messages, fp);
// Process each message
for (int i = 0; i < messages.length; i++)
{
if (!messages[i].isSet(Flags.Flag.SEEN))
process(messages[i]);
//messages[i].setFlag(Flags.Flag.DELETED, true);
}
folder.close(true);
store.close();
}
private static void process(Message message)
throws Exception
{
System.out.println("subject: " + message.getSubject()
+ ", sent: " + message.getSentDate()
+ ", size: " + message.getSize());
}
}
15. Java核心代码例程之:(EJB) Home Interface
/**
* Home interface for HelloWorldSessionBean
*
* @see HelloWorldSessionBean
**/
public interface HelloWorldSessionHome extends javax.ejb.EJBHome
{
HelloWorldSession create()
throws javax.ejb.CreateException,
java.rmi.RemoteException;
}
16. Java
核心代码例程之:
(EJB) Remote Interface
/**
* Remote interface for HelloWorldSessionBean
*
* @see HelloWorldSessionBean
**/
public interface HelloWorldSession extends javax.ejb.EJBObject
{
public String sayHello()
throws java.rmi.RemoteException;
}
17. Java核心代码例程之:(JAXP) DOM
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
/**
* DOMDemo uses JAXP to acquire a DocumentBuilder to build a DOM Document from an XML file.
* The example XML file represents a shopping cart.
*
* The following JARs must be in your CLASSPATH:
* - jaxp.jar
* - xerces.jar (for SAX parser and DOM object implementations)
*
* Download JAXP (which includes these JARs) here: http://java.sun.com/xml/
* Find additional Xerces info here: http://xml.apache.org/
*
**/
public class DOMDemo
{
public static void main( String[] args )
{
try
{
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
System.out.println( "DocumentBuilderFactory classname: " + factory.getClass().getName() );
DocumentBuilder builder = factory.newDocumentBuilder();
System.out.println( "DocumentBuilder classname: " + builder.getClass().getName() );
//parse the XML file and create the Document
Document document = builder.parse( "cart.xml" );
/*
At this point, all data in the XML file has been parsed and loaded into memory
in the form of a DOM Document object. The Document is a tree of Node objects.
This printNode() method simply recurses through a Node tree and displays info
about each node.**/
printNode( document, "" );
}
catch( Exception e )
{
e.printStackTrace();
}
}
/**
* printNode is a recursive method that prints info about each Node
* in a Node tree to System.out. Call it with the root Node of your Node tree and
* an initial indent of ""
**/
public static void printNode( Node node, String indent )
{
String text = null;
if( node.getNodeType() == Node.TEXT_NODE )
text = node.getNodeValue().trim();
else
text = node.getNodeName();
if( text.length() > 0 )
System.out.println( indent + getNodeTypeName( node ) + ": " + text );
NodeList childNodes = node.getChildNodes();
for( int i = 0; i < childNodes.getLength(); i++ )
printNode( childNodes.item( i ), indent + " " );
}
/**
* getNodeTypeName returns a String containing the type-name of the specified Node.
**/
public static String getNodeTypeName( Node node )
{
switch( node.getNodeType() )
{
case Node.TEXT_NODE:
return "TEXT";
case Node.ELEMENT_NODE:
return "ELEMENT";
case Node.ATTRIBUTE_NODE:
return "ATTRIBUTE";
case Node.ENTITY_NODE:
return "ENTITY";
case Node.DOCUMENT_NODE:
return "DOCUMENT";
case Node.CDATA_SECTION_NODE:
return "CDATA_SECTION";
case Node.COMMENT_NODE:
return "COMMENT";
case Node.NOTATION_NODE:
return "NOTATION";
case Node.PROCESSING_INSTRUCTION_NODE:
return "PROCESSING INSTRUCTION";
case Node.DOCUMENT_FRAGMENT_NODE:
return "DOCUMENT FRAGMENT";
case Node.ENTITY_REFERENCE_NODE:
return "ENTITY REFERENCE";
}
return "UNKNOWN NODE TYPE";
}
}
18. Java核心代码例程之:JNIExample.java
/**
* This class is a simple example that uses a native function
* @author Renga
**/
public class JNIExample {
static {
System.loadLibrary( "JNI" );
}
/**
* Native method declaration. Just returns the string "Hello World from JNI!"
* @return A string
**/
public native String sayHello();
/**
* Main method
* @param args Command-line arguments
**/
public static void main( String[] args ) {
// Create a new JNIExample object
JNIExample temp = new JNIExample();
// Invoke the native method
System.out.println( temp.sayHello() );
}
}
19. Java核心代码例程之:(JAXP) SAX
import javax.xml.parsers.*;
import org.xml.sax.*;
/**
* SAXDemo uses JAXP to acquire a SAX parser to parse an XML file.
* The example XML file represents a shopping cart.
*
* The following JARs must be in your CLASSPATH:
* - jaxp.jar
* - xerces.jar (for SAX parser implementation)
*
* Download JAXP (which includes these JARs) here: http://java.sun.com/xml/
* Find additional Xerces info here: http://xml.apache.org/
*
* Note: Unlike DOM, SAX parsing does not load the XML file into memory.
* SAX parsers traverse the XML file and report parse "events" to an event handler.
**/
public class SAXDemo
extends org.xml.sax.HandlerBase
{
/**
* main creates and runs a SaxTest instance.
**/
public static void main( String[] args )
{
SAXDemo me = new SAXDemo();
me.run();
}
public void run()
{
try
{
SAXParserFactory factory = SAXParserFactory.newInstance();
log( "SAXParserFactory classname: " + factory.getClass().getName() );
SAXParser saxParser = factory.newSAXParser();
log( "SAXParser classname: " + saxParser.getClass().getName() );
/*
The SAXParser.parse method initiates parsing of the XML file.
The second parameter specifies which class will handle parse events.
This class must extend org.xml.sax.HandlerBase
**/
saxParser.parse( "cart.xml", this );
}
catch( Exception e )
{
e.printStackTrace();
}
}
/**
* log simply prints the specified message to System.out
**/
public void log( String message )
{
System.out.println( message );
}
/**
* SAXParser calls startDocument() when it starts parsing a document
**/
public void startDocument ()
throws SAXException
{
log( "Start SAX parse" );
}
/**
* SAXParser calls endDocument() when it finishes parsing a document
**/
public void endDocument ()
throws SAXException
{
log( "End SAX parse" );
}
/**
* SAXParser calls startElement() when it encounters an opening element tag (eg <item>)
**/
public void startElement (String name, AttributeList attrs)
throws SAXException
{
log( "<" + name + ">" );
}
/**
* SAXParser calls endElement() when it encounters a closing element tag (eg </item>)
**/
public void endElement (String name)
throws SAXException
{
log( "</" + name + ">" );
}
/**
* SAXParser calls characters() when it encounters text outside of any tags
**/
public void characters(char[] p0, int p1, int p2)
throws SAXException
{
String str = new String( p0, p1, p2 ).trim();
if( str.length() > 0 )
log( str );
}
}
20.Java核心代码例程之:JavaMail----SmtpMail.java
import java.io.*;
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
public class SmtpMail
{
public static void main(String args[]) throws Exception
{
// create some properties and get the default Session
Properties props = new Properties();
props.put("mail.smtp.host", "yoursmtpserver");
Session session = Session.getDefaultInstance(props, null);
Message message = new MimeMessage(session);
// create a message
InternetAddress ia[] = new InternetAddress[1];
ia[0] = new InternetAddress("myself@abc.com", "Me");
message.setFrom(new InternetAddress("test@abc.com", "some developer"));
message.setRecipients(Message.RecipientType.TO, ia);
message.setSubject("Hello World");
message.setText("Hello World! This message was generated using JavaMail.");
message.saveChanges();
Transport transport = session.getTransport("smtp");
transport.connect();
transport.send(message);
}
}
21. Java核心代码例程之:JNIExample.java
/* DO NOT EDIT THIS FILE - it is machine generated **/
#include <jni.h>
/* Header for class JNIExample **/
#ifndef _Included_JNIExample
#define _Included_JNIExample
#ifdef __cplusplus
extern "C" {
#endif
/*
* Class: JNIExample
* Method: sayHello
* Signature: ()Ljava/lang/String;
**/
JNIEXPORT jstring JNICALL Java_JNIExample_sayHello
(JNIEnv *, jobject);
#ifdef __cplusplus
}
#endif
#endif
22.Java核心代码例程之:(JAXP) cart.xml
<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:template match="/">
<html>
<head>
<title>Shopping Cart</title>
</head>
<body>
<h1>Shopping Cart</h1>
<table border="1">
<tr>
<td><b>ID</b></td>
<td><b>Make</b></td>
<td><b>Model</b></td>
<td><b>Price</b></td>
<td><b>Count</b></td>
</tr>
<xsl:for-each select="cart/item">
<tr>
<td><xsl:value-of select="id"/></td>
<td><xsl:value-of select="make"/></td>
<td><xsl:value-of select="model"/></td>
<td><xsl:value-of select="price"/></td>
<td><xsl:value-of select="count"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>
23. Java核心代码例程之:(JAXP) XSL Transformation
import javax.xml.transform.*;
import javax.xml.transform.stream.*;
/**
* TransformDemo uses JAXP to acquire an XML Transformer. It uses the Transformer
* to transform an XML shopping cart into an HTML view of the shopping cart.
* The Transformer uses transform instructions in an XSLT (.xsl) file.
*
* The following JARs must be in your CLASSPATH:
* - jaxp.jar
* - xerces.jar (for SAX parser and DOM object implementations)
* - xalan.jar (for XSLT implementation)
*
* Download JAXP (which includes these JARs) here: http://java.sun.com/xml/
* Find additional Xerces and Xalan info here: http://xml.apache.org/
*
* Note: XSLT authoring/programming is beyond the scope of this tutorial.
* You"ll find good XSL info here: http://www.w3.org/Style/XSL/#learning
**/
public class TransformDemo
{
public static void main( String[] args )
{
try
{
TransformerFactory factory = TransformerFactory.newInstance();
System.out.println( "TransformerFactory classname: " + factory.getClass().getName() );
Transformer transformer = factory.newTransformer( new StreamSource( "cart.xsl" ) );
System.out.println( "Transformer classname: " + transformer.getClass().getName() );
//This single line applies the XSL file to transform the XML into HTML.
transformer.transform( new StreamSource( "cart.xml" ), new StreamResult( System.out ) );
}
catch( Exception e )
{
e.printStackTrace();
}
}
}