Java core code routine

xiaoxiao2021-03-06  44

Java core code routine

1.java core code routine: 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's core code routine: 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 core code routines: 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's core code routine: VectorDemo.javaimport 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 ("david"); v.addeElement ("PAM"); v.addeElement ("joe"); for (int i = 0; i

5. Java core code routines: jdbc.javaimport java.sql. *; / ** * Simple demo of how to perform a sql query useing 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 core code routine: rmiexampleServer.javaimport java.rmi. *; Import java.rmi.server. *; / ** * this class is a simple escLle of a RMI Server * @Author Re nga ** / public class RMIExampleServer extends UnicastRemoteObject implements RMIExample {/ ** * Do nothing constructor * @throws RemoteException ** / public RMIExampleServer () throws RemoteException {System.out.println ( "RMIExampleServer :: cntr");} / * * @Return World from RMI! "* @Return a string * @throws remoteexception ** / public string sayhello () throws remoteException {return" Hello World from RMI! ";}}

7. Java's core code routine:.. CalendarDemo.javaimport 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.Mont) "/" Cal.Get (Calendar.day_Of_Month) "/" Cal.get (Calendar.Year));}} 8. Java core code routine: PropertiesDemo.javaimport java.util. *; Import java.io. *; / ** * Demonstrates how to sort strings. ** * / public class protectiesdemo {public static void main (string args []) throws exception {Properties PROPS = new profment (); 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 VAL UE if found, OtherWise "None" system.out.println (Props.getProperty, "None")); / * // You can Also Load Properties from a file fileinputstream FII = New fileinputstream ("My" .properties "); PrOPS.LOAD (FIS); fis.close (); ** /}}

9. Java's core code routine: 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 () {// loop 10 Times for (INT i = startingnumber; i <(startingnumber 100); i ) System.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 the core code routine: RMIExampleSetup.javaimport 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 v oid 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's core code routine: RMIExample.javaimport 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 core code routine: java.policygrant {permission java.security.Allpermission;}; 13. Java core code routine: showfilecontent.javaimport java.io. *; // read a file useing buffredreader.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 core code routines: javamail ---- popmail.javaimport 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.getFolder (" inbox "); if (folder == null) throw new nullpointersException (" Unable to get folder: folde R); // Get Message Count Folder.open (Folder.Read_Write); int totalmessages = folder.getMessageCount (); if (TotalMessages == 0) {system.out.println ("no message found in in inbox); Folder .close (false); store.close (); return;} // Get Attributes & flags for all messages = folder.getMess (); 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

/ ** * Home interface for HelloWorldSessionBean * * @see HelloWorldSessionBean ** / public interface HelloWorldSessionHome extends javax.ejb.EJBHome {HelloWorldSession create () throws javax.ejb.CreateException, java.rmi.RemoteException;}

16. Java

Core code routine:

(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 core code routines: (JAX) DomImPort 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 D Ocument = 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 trecess. 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 inTIAL 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

18. Java core code routine: jniexample.java / ** * this class is a simple example this class 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 ());}}

19. Java core code routine: (JAX) SAXIMPORT JAVAX.XML.PARSERS. *; Import Org.xml.sax. *; / ** * Saxdemo Usess 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 off detes 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 (). ge tName ()); 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 ) ** / public void StarTelement (String Name, AttributeList Attrs) throws saxception {log ("<" name ">);} / ** * saxparser calls endelement () WHEN IT ENCOUNTERS A Closing Element Tag (EG ) ** / public void endElement (String name) throws SAXException {log ( "");} / ** * SAXParser calls characters () when it encounters text outside of any tags ** / public void characters ( Char [] P0, INT P1, INT P2) throws saxception {string str = new string (P0, P1, P2) .TRIM (); IF (str.Length ()> 0) log (str);}}

20. Java core code routines: javamail ---- smtpmail.javaimport 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 Internetdress (" Test@abc.com "," Some Developer "); Message. RecipientType.to, IA); Message.setSubject "Hello World"); Message.Settext ("Hello World! This Message Was Generated Using JavaMail."); Message.SAVEChanges (); Trans Port transport = session.getTransport ("smtp"); transport.connect (); transport.send (message);}} 21. Java core code routine: jniexample.java/* do not Edit this file - IT is Machine generated ** / #include / * 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

twenty two. Java core code routine: (jaxp) Cart.xml 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: styletet></p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-55795.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="55795" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.254</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = '5IXvh_2BbQHwRnteqoj95qgCeaeo26dfKNjFIT1TrxYTOKnOOYT0zTvtabryBfUMnX_2F8e_2F5p5UKNiGV_2FE5KtqgWg_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>