现在的位置: 首页 > 综合 > 正文

一些java实例

2018年04月27日 ⁄ 综合 ⁄ 共 27294字 ⁄ 字号 评论关闭
  1. package test41;  
  2.   
  3. import java.io.*;  
  4. /** 
  5.  * Title: 运行系统命令 
  6.  * Description:运行一个系统的命令,演示使用Runtime类。 
  7.  * Filename: CmdExec.java 
  8.  */  
  9. public class CmdExec {  
  10. /** 
  11.  *方法说明:构造器,运行系统命令 
  12.  *输入参数:String cmdline 命令字符 
  13.  *返回类型: 
  14.  */  
  15.   public CmdExec(String cmdline) {  
  16.     try {  
  17.      String line;  
  18.      //运行系统命令  
  19.      Process p = Runtime.getRuntime().exec(cmdline);  
  20.      //使用缓存输入流获取屏幕输出。  
  21.      BufferedReader input =   
  22.        new BufferedReader  
  23.          (new InputStreamReader(p.getInputStream()));  
  24.      //读取屏幕输出  
  25.      while ((line = input.readLine()) != null) {  
  26.        System.out.println("java print:"+line);  
  27.        }  
  28.      //关闭输入流  
  29.      input.close();  
  30.      }   
  31.     catch (Exception err) {  
  32.      err.printStackTrace();  
  33.      }  
  34.    }  
  35. /** 
  36.  *方法说明:主方法 
  37.  *输入参数: 
  38.  *返回类型: 
  39.  */  
  40. public static void main(String argv[]) {  
  41.    new CmdExec("myprog.bat");  
  42.   }  
  43. }  
  1. package test43;  
  2.   
  3. import java.io.*;  
  4. import java.net.*;   
  5. /** 
  6.  * Title: 简单服务器客户端 
  7.  * Description: 本程序是一个简单的客户端,用来和服务器连接 
  8.  * Filename: SampleClient.java 
  9.  */  
  10. public class SampleClient {  
  11.     public static void main(String[] arges) {  
  12.         try {  
  13.             // 获取一个IP。null表示本机  
  14.             InetAddress addr = InetAddress.getByName(null);  
  15.             // 打开8888端口,与服务器建立连接  
  16.             Socket sk = new Socket(addr, 8888);  
  17.             // 缓存输入  
  18.             BufferedReader in = new BufferedReader(new InputStreamReader(sk  
  19.                     .getInputStream()));  
  20.             // 缓存输出  
  21.             PrintWriter out = new PrintWriter(new BufferedWriter(  
  22.                     new OutputStreamWriter(sk.getOutputStream())), true);  
  23.             // 向服务器发送信息  
  24.             out.println("你好!");  
  25.             // 接收服务器信息  
  26.             System.out.println(in.readLine());  
  27.         } catch (Exception e) {  
  28.             System.out.println(e);  
  29.         }  
  30.     }  
  31. }  

  1. package test43;  
  2.   
  3. import java.net.*;  
  4. import java.io.*;  
  5. /** 
  6.  * Title: 简单服务器服务端 
  7.  * Description: 这是一个简单的服务器端程序 
  8.  * Filename: SampleServer.java 
  9.  */  
  10. public class SampleServer {  
  11.     public static void main(String[] arges) {  
  12.         try {  
  13.             int port = 8888;  
  14.             // 使用8888端口创建一个ServerSocket  
  15.             ServerSocket mySocket = new ServerSocket(port);  
  16.             // 等待监听是否有客户端连接  
  17.             Socket sk = mySocket.accept();  
  18.             // 输入缓存  
  19.             BufferedReader in = new BufferedReader(new InputStreamReader(sk  
  20.                     .getInputStream()));  
  21.             // 输出缓存  
  22.             PrintWriter out = new PrintWriter(new BufferedWriter(  
  23.                     new OutputStreamWriter(sk.getOutputStream())), true);  
  24.             // 打印接收到的客户端发送过来的信息  
  25.             System.out.println("客户端信息:" + in.readLine());  
  26.             // 向客户端回信息  
  27.             out.println("你好,我是服务器。我使用的端口号: " + port);  
  28.         } catch (Exception e) {  
  29.             System.out.println(e);  
  30.         }  
  31.     }  
  32. }  

  1. package test44;  
  2. // 文件名:moreServer.java  
  3. import java.io.*;  
  4. import java.net.*;  
  5. /** 
  6.  * Title: 多线程服务器 
  7.  * Description: 本实例使用多线程实现多服务功能。 
  8.  * Filename:  
  9.  */  
  10. class moreServer  
  11. {  
  12.  public static void main (String [] args) throws IOException  
  13.  {  
  14.    System.out.println ("Server starting...\n");   
  15.    //使用8000端口提供服务  
  16.    ServerSocket server = new ServerSocket (8000);  
  17.    while (true)  
  18.    {  
  19.     //阻塞,直到有客户连接  
  20.      Socket sk = server.accept ();  
  21.      System.out.println ("Accepting Connection...\n");  
  22.      //启动服务线程  
  23.      new ServerThread (sk).start ();  
  24.    }  
  25.  }  
  26. }  
  27. //使用线程,为多个客户端服务  
  28. class ServerThread extends Thread  
  29. {  
  30.  private Socket sk;  
  31.    
  32.  ServerThread (Socket sk)  
  33.  {  
  34.   this.sk = sk;  
  35.  }  
  36. //线程运行实体  
  37.  public void run ()  
  38.  {  
  39.   BufferedReader in = null;  
  40.   PrintWriter out = null;  
  41.   try{  
  42.     InputStreamReader isr;  
  43.     isr = new InputStreamReader (sk.getInputStream ());  
  44.     in = new BufferedReader (isr);  
  45.     out = new PrintWriter (  
  46.            new BufferedWriter(  
  47.             new OutputStreamWriter(  
  48.               sk.getOutputStream ())), true);  
  49.   
  50.     while(true){  
  51.       //接收来自客户端的请求,根据不同的命令返回不同的信息。  
  52.       String cmd = in.readLine ();  
  53.       System.out.println(cmd);  
  54.       if (cmd == null)  
  55.           break;  
  56.       cmd = cmd.toUpperCase ();  
  57.       if (cmd.startsWith ("BYE")){  
  58.          out.println ("BYE");  
  59.          break;  
  60.       }else{  
  61.         out.println ("你好,我是服务器!");  
  62.       }  
  63.     }  
  64.     }catch (IOException e)  
  65.     {  
  66.        System.out.println (e.toString ());  
  67.     }  
  68.     finally  
  69.     {  
  70.       System.out.println ("Closing Connection...\n");  
  71.       //最后释放资源  
  72.       try{  
  73.        if (in != null)  
  74.          in.close ();  
  75.        if (out != null)  
  76.          out.close ();  
  77.         if (sk != null)  
  78.           sk.close ();  
  79.       }  
  80.       catch (IOException e)  
  81.       {  
  82.         System.out.println("close err"+e);  
  83.       }  
  84.     }  
  85.  }  
  86. }  

  1. package test44;  
  2.   
  3. //文件名:SocketClient.java  
  4. import java.io.*;  
  5. import java.net.*;  
  6.   
  7. class SocketThreadClient extends Thread {  
  8.     public static int count = 0;  
  9.   
  10.     // 构造器,实现服务  
  11.     public SocketThreadClient(InetAddress addr) {  
  12.         count++;  
  13.         BufferedReader in = null;  
  14.         PrintWriter out = null;  
  15.         Socket sk = null;  
  16.         try {  
  17.             // 使用8000端口  
  18.             sk = new Socket(addr, 8000);  
  19.             InputStreamReader isr;  
  20.             isr = new InputStreamReader(sk.getInputStream());  
  21.             in = new BufferedReader(isr);  
  22.             // 建立输出  
  23.             out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(sk  
  24.                     .getOutputStream())), true);  
  25.             // 向服务器发送请求  
  26.             System.out.println("count:" + count);  
  27.             out.println("Hello");  
  28.             System.out.println(in.readLine());  
  29.             out.println("BYE");  
  30.             System.out.println(in.readLine());  
  31.   
  32.         } catch (IOException e) {  
  33.             System.out.println(e.toString());  
  34.         } finally {  
  35.             out.println("END");  
  36.             // 释放资源  
  37.             try {  
  38.                 if (in != null)  
  39.                     in.close();  
  40.                 if (out != null)  
  41.                     out.close();  
  42.                 if (sk != null)  
  43.                     sk.close();  
  44.             } catch (IOException e) {  
  45.             }  
  46.         }  
  47.     }  
  48. }  
  49.   
  50. // 客户端  
  51. public class SocketClient {  
  52.     @SuppressWarnings("static-access")  
  53.     public static void main(String[] args) throws IOException,  
  54.             InterruptedException {  
  55.         InetAddress addr = InetAddress.getByName(null);  
  56.         for (int i = 0; i < 10; i++)  
  57.             new SocketThreadClient(addr);  
  58.         Thread.currentThread().sleep(1000);  
  59.     }  
  60. }  

  1. package test45;  
  2.   
  3. import java.net.*;  
  4. import java.io.*;  
  5. /** 
  6.  * Title: 使用SMTP发送邮件 
  7.  * Description: 本实例通过使用socket方式,根据SMTP协议发送邮件 
  8.  * Copyright: Copyright (c) 2003 
  9.  * Filename: sendSMTPMail.java 
  10.  */  
  11. public class sendSMTPMail {  
  12. /** 
  13.  *方法说明:主方法 
  14.  *输入参数:1。服务器ip;2。对方邮件地址 
  15.  *返回类型: 
  16.  */   
  17.   
  18.     public static void main(String[] arges) {  
  19.         if (arges.length != 2) {  
  20.             System.out.println("use java sendSMTPMail hostname | mail to");  
  21.             return;  
  22.         }  
  23.         sendSMTPMail t = new sendSMTPMail();  
  24.         t.sendMail(arges[0], arges[1]);  
  25.     }  
  26. /** 
  27.  *方法说明:发送邮件 
  28.  *输入参数:String mailServer 邮件接收服务器 
  29.  *输入参数:String recipient 接收邮件的地址 
  30.  *返回类型: 
  31.  */  
  32.     public void sendMail(String mailServer, String recipient) {  
  33.         try {  
  34.             // 有Socket打开25端口  
  35.             Socket s = new Socket(mailServer, 25);  
  36.             // 缓存输入和输出  
  37.             BufferedReader in = new BufferedReader(new InputStreamReader(s  
  38.                     .getInputStream(), "8859_1"));  
  39.             BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s  
  40.                     .getOutputStream(), "8859_1"));  
  41.             // 发出“HELO”命令,表示对服务器的问候  
  42.             send(in, out, "HELO theWorld");  
  43.             // 告诉服务器我的邮件地址,有些服务器要校验这个地址  
  44.             send(in, out, "MAIL FROM: <213@qq.com>");  
  45.             // 使用“RCPT TO”命令告诉服务器解释邮件的邮件地址  
  46.             send(in, out, "RCPT TO: " + recipient);  
  47.             // 发送一个“DATA”表示下面将是邮件主体  
  48.             send(in, out, "DATA");  
  49.             // 使用Subject命令标注邮件主题  
  50.             send(out, "Subject: 这是一个测试程序!");  
  51.             // 使用“From”标注邮件的来源  
  52.             send(out, "From: riverwind <213@qq.com>");  
  53.             send(out, "\n");  
  54.             // 邮件主体  
  55.             send(out, "这是一个使用SMTP协议发送的邮件!如果打扰请删除!");  
  56.             send(out, "\n.\n");  
  57.             // 发送“QUIT”端口邮件的通讯  
  58.             send(in, out, "QUIT");  
  59.             s.close();  
  60.         } catch (Exception e) {  
  61.             e.printStackTrace();  
  62.         }  
  63.     }  
  64. /** 
  65.  *方法说明:发送信息,并接收回信 
  66.  *输入参数: 
  67.  *返回类型: 
  68.  */  
  69.     public void send(BufferedReader in, BufferedWriter out, String s) {  
  70.         try {  
  71.             out.write(s + "\n");  
  72.             out.flush();  
  73.             System.out.println(s);  
  74.             s = in.readLine();  
  75.             System.out.println(s);  
  76.         } catch (Exception e) {  
  77.             e.printStackTrace();  
  78.         }  
  79.     }  
  80. /** 
  81.  *方法说明:重载方法。向socket写入信息 
  82.  *输入参数:BufferedWriter out 输出缓冲器 
  83.  *输入参数:String s 写入的信息 
  84.  *返回类型: 
  85.  */  
  86.  public void send(BufferedWriter out, String s) {  
  87.    try {  
  88.       out.write(s + "\n");  
  89.       out.flush();  
  90.       System.out.println(s);  
  91.       }  
  92.    catch (Exception e) {  
  93.       e.printStackTrace();  
  94.       }  
  95.    }  
  96. }  

  1. package test46;  
  2. import java.io.*;  
  3. import java.net.*;  
  4. /** 
  5.  * Title: SMTP协议接收邮件 
  6.  * Description: 通过Socket连接POP3服务器,使用SMTP协议接收邮件服务器中的邮件 
  7.  * Filename:  
  8.  */  
  9. class POP3Demo  
  10. {  
  11. /** 
  12.  *方法说明:主方法,接收用户输入 
  13.  *输入参数: 
  14.  *返回类型: 
  15.  */  
  16.   @SuppressWarnings("static-access")  
  17. public static void main(String[] args){  
  18.     if(args.length!=3){  
  19.      System.out.println("USE: java POP3Demo mailhost user password");  
  20.     }  
  21.     new POP3Demo().receive(args[0],args[1],args[2]);  
  22.   }  
  23. /** 
  24.  *方法说明:接收邮件 
  25.  *输入参数:String popServer 服务器地址 
  26.  *输入参数:String popUser 邮箱用户名 
  27.  *输入参数:String popPassword 邮箱密码 
  28.  *返回类型: 
  29.  */  
  30.   public static void receive (String popServer, String popUser, String popPassword)  
  31.   {  
  32.    String POP3Server = popServer;  
  33.    int POP3Port = 110;  
  34.    Socket client = null;  
  35.    try  
  36.    {  
  37.      // 创建一个连接到POP3服务程序的套接字。  
  38.      client = new Socket (POP3Server, POP3Port);  
  39.      //创建一个BufferedReader对象,以便从套接字读取输出。  
  40.      InputStream is = client.getInputStream ();  
  41.      BufferedReader sockin;  
  42.      sockin = new BufferedReader (new InputStreamReader (is));  
  43.      //创建一个PrintWriter对象,以便向套接字写入内容。  
  44.      OutputStream os = client.getOutputStream ();  
  45.      PrintWriter sockout;  
  46.      sockout = new PrintWriter (os, true); // true for auto-flush  
  47.      // 显示POP3握手信息。  
  48.      System.out.println ("S:" + sockin.readLine ());  
  49.        
  50.      /*--   与POP3服务器握手过程   --*/       
  51.       System.out.print ("C:");  
  52.       String cmd = "user "+popUser;  
  53.       // 将用户名发送到POP3服务程序。  
  54.       System.out.println (cmd);  
  55.       sockout.println (cmd);  
  56.       // 读取POP3服务程序的回应消息。  
  57.       String reply = sockin.readLine ();  
  58.       System.out.println ("S:" + reply);  
  59.   
  60.       System.out.print ("C:");  
  61.       cmd = "pass ";  
  62.       // 将密码发送到POP3服务程序。  
  63.       System.out.println(cmd+"*********");  
  64.       sockout.println (cmd+popPassword);  
  65.       // 读取POP3服务程序的回应消息。  
  66.       reply = sockin.readLine ();  
  67.       System.out.println ("S:" + reply);  
  68.         
  69.              
  70.       System.out.print ("C:");  
  71.       cmd = "stat";  
  72.       // 获取邮件数据。  
  73.       System.out.println(cmd);  
  74.       sockout.println (cmd);  
  75.       // 读取POP3服务程序的回应消息。  
  76.       reply = sockin.readLine ();  
  77.       System.out.println ("S:" + reply);  
  78.       if(reply==nullreturn;  
  79.       System.out.print ("C:");  
  80.       cmd = "retr 1";  
  81.       // 将接收第一丰邮件命令发送到POP3服务程序。  
  82.       System.out.println(cmd);  
  83.       sockout.println (cmd);  
  84.         
  85.       // 输入了RETR命令并且返回了成功的回应码,持续从套接字读取输出,   
  86.       // 直到遇到<CRLF>.<CRLF>。这时从套接字读出的输出就是邮件的内容。  
  87.       if (cmd.toLowerCase ().startsWith ("retr") &&  
  88.         reply.charAt (0) == '+')  
  89.         do  
  90.         {  
  91.           reply = sockin.readLine ();  
  92.           System.out.println ("S:" + reply);  
  93.           if (reply != null && reply.length () > 0)  
  94.             if (reply.charAt (0) == '.')  
  95.               break;  
  96.         }  
  97.         while (true);  
  98.       cmd = "quit";  
  99.       // 将命令发送到POP3服务程序。  
  100.       System.out.print (cmd);  
  101.       sockout.println (cmd);       
  102.    }  
  103.    catch (IOException e)  
  104.    {  
  105.      System.out.println (e.toString ());  
  106.    }  
  107.    finally  
  108.    {  
  109.      try  
  110.      {  if (client != null)  
  111.           client.close ();  
  112.      }  
  113.      catch (IOException e)  
  114.      {  
  115.      }  
  116.    }  
  117.   }  
  118. }  

  1. package test47;  
  2.   
  3. import java.util.*;  
  4. import javax.mail.*;  
  5. import javax.mail.internet.*;  
  6. import javax.activation.*;  
  7.   
  8. /** 
  9.  * Title: 使用javamail发送邮件 Description: 演示如何使用javamail包发送电子邮件。这个实例可发送多附件 Filename: 
  10.  * Mail.java 
  11.  */  
  12. public class Mail {  
  13.   
  14.     String to = "";// 收件人  
  15.     String from = "";// 发件人  
  16.     String host = "";// smtp主机  
  17.     String username = "";  
  18.     String password = "";  
  19.     String filename = "";// 附件文件名  
  20.     String subject = "";// 邮件主题  
  21.     String content = "";// 邮件正文  
  22.     @SuppressWarnings("unchecked")  
  23.     Vector file = new Vector();// 附件文件集合  
  24.   
  25.     /** 
  26.      *方法说明:默认构造器 输入参数: 返回类型: 
  27.      */  
  28.     public Mail() {  
  29.     }  
  30.   
  31.     /** 
  32.      *方法说明:构造器,提供直接的参数传入 输入参数: 返回类型: 
  33.      */  
  34.     public Mail(String to, String from, String smtpServer, String username,  
  35.             String password, String subject, String content) {  
  36.         this.to = to;  
  37.         this.from = from;  
  38.         this.host = smtpServer;  
  39.         this.username = username;  
  40.         this.password = password;  
  41.         this.subject = subject;  
  42.         this.content = content;  
  43.     }  
  44.   
  45.     /** 
  46.      *方法说明:设置邮件服务器地址 输入参数:String host 邮件服务器地址名称 返回类型: 
  47.      */  
  48.     public void setHost(String host) {  
  49.         this.host = host;  
  50.     }  
  51.   
  52.     /** 
  53.      *方法说明:设置登录服务器校验密码 输入参数: 返回类型: 
  54.      */  
  55.     public void setPassWord(String pwd) {  
  56.         this.password = pwd;  
  57.     }  
  58.   
  59.     /** 
  60.      *方法说明:设置登录服务器校验用户 输入参数: 返回类型: 
  61.      */  
  62.     public void setUserName(String usn) {  
  63.         this.username = usn;  
  64.     }  
  65.   
  66.     /** 
  67.      *方法说明:设置邮件发送目的邮箱 输入参数: 返回类型: 
  68.      */  
  69.     public void setTo(String to) {  
  70.         this.to = to;  
  71.     }  
  72.   
  73.     /** 
  74.      *方法说明:设置邮件发送源邮箱 输入参数: 返回类型: 
  75.      */  
  76.     public void setFrom(String from) {  
  77.         this.from = from;  
  78.     }  
  79.   
  80.     /** 
  81.      *方法说明:设置邮件主题 输入参数: 返回类型: 
  82.      */  
  83.     public void setSubject(String subject) {  
  84.         this.subject = subject;  
  85.     }  
  86.   
  87.     /** 
  88.      *方法说明:设置邮件内容 输入参数: 返回类型: 
  89.      */  
  90.     public void setContent(String content) {  
  91.         this.content = content;  
  92.     }  
  93.   
  94.     /** 
  95.      *方法说明:把主题转换为中文 输入参数:String strText 返回类型: 
  96.      */  
  97.     public String transferChinese(String strText) {  
  98.         try {  
  99.             strText = MimeUtility.encodeText(new String(strText.getBytes(),  
  100.                     "GB2312"), "GB2312""B");  
  101.         } catch (Exception e) {  
  102.             e.printStackTrace();  
  103.         }  
  104.         return strText;  
  105.     }  
  106.   
  107.     /** 
  108.      *方法说明:往附件组合中添加附件 输入参数: 返回类型: 
  109.      */  
  110.     public void attachfile(String fname) {  
  111.         file.addElement(fname);  
  112.     }  
  113.   
  114.     /** 
  115.      *方法说明:发送邮件 输入参数: 返回类型:boolean 成功为true,反之为false 
  116.      */  
  117.     public boolean sendMail() {  
  118.   
  119.         // 构造mail session  
  120.         Properties props = System.getProperties();  
  121.         props.put("mail.smtp.host", host);  
  122.         props.put("mail.smtp.auth""true");  
  123.         Session session = Session.getDefaultInstance(props,  
  124.                 new Authenticator() {  
  125.                     public PasswordAuthentication getPasswordAuthentication() {  
  126.                         return new PasswordAuthentication(username, password);  
  127.                     }  
  128.                 });  
  129.   
  130.         try {  
  131.             // 构造MimeMessage 并设定基本的值  
  132.             MimeMessage msg = new MimeMessage(session);  
  133.             msg.setFrom(new InternetAddress(from));  
  134.             InternetAddress[] address = { new InternetAddress(to) };  
  135.             msg.setRecipients(Message.RecipientType.TO, address);  
  136.             subject = transferChinese(subject);  
  137.             msg.setSubject(subject);  
  138.   
  139.             // 构造Multipart  
  140.             Multipart mp = new MimeMultipart();  
  141.   
  142.             // 向Multipart添加正文  
  143.             MimeBodyPart mbpContent = new MimeBodyPart();  
  144.             mbpContent.setText(content);  
  145.             // 向MimeMessage添加(Multipart代表正文)  
  146.             mp.addBodyPart(mbpContent);  
  147.   
  148.             // 向Multipart添加附件  
  149.             Enumeration efile = file.elements();  
  150.             while (efile.hasMoreElements()) {  
  151.   
  152.                 MimeBodyPart mbpFile = new MimeBodyPart();  
  153.                 filename = efile.nextElement().toString();  
  154.                 FileDataSource fds = new FileDataSource(filename);  
  155.                 mbpFile.setDataHandler(new DataHandler(fds));  
  156.                 mbpFile.setFileName(fds.getName());  
  157.                 // 向MimeMessage添加(Multipart代表附件)  
  158.                 mp.addBodyPart(mbpFile);  
  159.   
  160.             }  
  161.   
  162.             file.removeAllElements();  
  163.             // 向Multipart添加MimeMessage  
  164.             msg.setContent(mp);  
  165.             msg.setSentDate(new Date());  
  166.             // 发送邮件  
  167.             Transport.send(msg);  
  168.   
  169.         } catch (MessagingException mex) {  
  170.             mex.printStackTrace();  
  171.             Exception ex = null;  
  172.             if ((ex = mex.getNextException()) != null) {  
  173.                 ex.printStackTrace();  
  174.             }  
  175.             return false;  
  176.         }  
  177.         return true;  
  178.     }  
  179.   
  180.     /** 
  181.      *方法说明:主方法,用于测试 输入参数: 返回类型: 
  182.      */  
  183.     public static void main(String[] args) {  
  184.         Mail sendmail = new Mail();  
  185.         sendmail.setHost("smtp.sohu.com");  
  186.         sendmail.setUserName("du_jiang");  
  187.         sendmail.setPassWord("31415926");  
  188.         sendmail.setTo("dujiang@sricnet.com");  
  189.         sendmail.setFrom("du_jiang@sohu.com");  
  190.         sendmail.setSubject("你好,这是测试!");  
  191.         sendmail.setContent("你好这是一个带多附件的测试!");  
  192.         // Mail sendmail = new  
  193.         // Mail("dujiang@sricnet.com","du_jiang@sohu.com","smtp.sohu.com","du_jiang","31415926","你好","胃,你好吗?");  
  194.         sendmail.attachfile("c:\\test.txt");  
  195.         sendmail.attachfile("DND.jar");  
  196.         sendmail.sendMail();  
  197.   
  198.     }  
  199. }// end  

  1. package test48;  
  2.   
  3. import javax.mail.*;  
  4. import javax.mail.internet.*;  
  5. import java.util.*;  
  6. import java.io.*;  
  7. /** 
  8.  * Title: 使用JavaMail接收邮件 
  9.  * Description: 实例JavaMail包接收邮件,本实例没有实现接收邮件的附件。 
  10.  * Filename: POPMail.java 
  11.  */  
  12. public class POPMail{  
  13. /** 
  14.  *方法说明:主方法,接收用户输入的邮箱服务器、用户名和密码 
  15.  *输入参数: 
  16.  *返回类型: 
  17.  */  
  18.     public static void main(String args[]){  
  19.         try{  
  20.             String popServer=args[0];  
  21.             String popUser=args[1];  
  22.             String popPassword=args[2];  
  23.             receive(popServer, popUser, popPassword);  
  24.         }catch (Exception ex){  
  25.             System.out.println("Usage: java com.lotontech.mail.POPMail"+" popServer popUser popPassword");  
  26.         }  
  27.         System.exit(0);  
  28.     }   
  29. /** 
  30.  *方法说明:接收邮件信息 
  31.  *输入参数: 
  32.  *返回类型: 
  33.  */  
  34.     public static void receive(String popServer, String popUser, String popPassword){  
  35.         Store store=null;  
  36.         Folder folder=null;  
  37.         try{  
  38.             //获取默认会话  
  39.             Properties props = System.getProperties();  
  40.             Session session = Session.getDefaultInstance(props, null);  
  41.             //使用POP3会话机制,连接服务器  
  42.             store = session.getStore("pop3");  
  43.             store.connect(popServer, popUser, popPassword);  
  44.             //获取默认文件夹  
  45.             folder = store.getDefaultFolder();  
  46.             if (folder == nullthrow new Exception("No default folder");  
  47.             //如果是收件箱  
  48.             folder = folder.getFolder("INBOX");  
  49.             if (folder == nullthrow new Exception("No POP3 INBOX");  
  50.             //使用只读方式打开收件箱  
  51.             folder.open(Folder.READ_ONLY);  
  52.             //得到文件夹信息,获取邮件列表  
  53.             Message[] msgs = folder.getMessages();  
  54.             for (int msgNum = 0; msgNum < msgs.length; msgNum++){  
  55.                 printMessage(msgs[msgNum]);  
  56.             }  
  57.         }catch (Exception ex){  
  58.             ex.printStackTrace();  
  59.         }  
  60.         finally{  
  61.         //释放资源  
  62.             try{  
  63.                 if (folder!=null) folder.close(false);  
  64.                 if (store!=null) store.close();  
  65.             }catch (Exception ex2) {  
  66.                 ex2.printStackTrace();  
  67.             }  
  68.         }  
  69.     }  
  70. /** 
  71.  *方法说明:打印邮件信息 
  72.  *输入参数:Message message 信息对象 
  73.  *返回类型: 
  74.  */  
  75.     public static void printMessage(Message message){  
  76.         try{  
  77.             //获得发送邮件地址  
  78.             String from=((InternetAddress)message.getFrom()[0]).getPersonal();  
  79.             if (from==null) from=((InternetAddress)message.getFrom()[0]).getAddress();  
  80.             System.out.println("FROM: "+from);  
  81.             //获取主题  
  82.             String subject=message.getSubject();  
  83.             System.out.println("SUBJECT: "+subject);  
  84.             //获取信息对象  
  85.             Part messagePart=message;  
  86.             Object content=messagePart.getContent();  
  87.             //附件  
  88.             if (content instanceof Multipart){  
  89.                 messagePart=((Multipart)content).getBodyPart(0);  
  90.                 System.out.println("[ Multipart Message ]");  
  91.             }  
  92.             //获取content类型  
  93.             String contentType=messagePart.getContentType();  
  94.             //如果邮件内容是纯文本或者是HTML,那么打印出信息  
  95.             System.out.println("CONTENT:"+contentType);  
  96.             if (contentType.startsWith("text/plain")||  
  97.                 contentType.startsWith("text/html")){  
  98.                 InputStream is = messagePart.getInputStream();  
  99.                 BufferedReader reader=new BufferedReader(new InputStreamReader(is));  
  100.                 String thisLine=reader.readLine();  
  101.                 while (thisLine!=null){  
  102.                     System.out.println(thisLine);  
  103.                     thisLine=reader.readLine();  
  104.                 }  
  105.             }  
  106.             System.out.println("-------------- END ---------------");  
  107.         }catch (Exception ex){  
  108.             ex.printStackTrace();  
  109.         }  
  110.     }  
  111. }  

  1. package test49;  
  2.   
  3. import java.io.*;  
  4. import java.net.*;  
  5.   
  6. /** 
  7.  * Title: 获取一个URL文本 
  8.  * Description: 通过使用URL类,构造一个输入对象,并读取其内容。 
  9.  * Filename: getURL.java 
  10.  */  
  11. public class getURL{  
  12.   
  13.  public static void main(String[] arg){  
  14.   if(arg.length!=1){  
  15.     System.out.println("USE java getURL  url");  
  16.     return;  
  17.   }  
  18.   new getURL(arg[0]);  
  19.  }  
  20. /** 
  21.  *方法说明:构造器 
  22.  *输入参数:String URL 互联网的网页地址。 
  23.  *返回类型: 
  24.  */  
  25.  public getURL(String URL){  
  26.     try {  
  27.         //创建一个URL对象  
  28.         URL url = new URL(URL);  
  29.       
  30.         //读取从服务器返回的所有文本  
  31.         BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));  
  32.         String str;  
  33.         while ((str = in.readLine()) != null) {  
  34.             //这里对文本出来  
  35.             display(str);  
  36.         }  
  37.         in.close();  
  38.     } catch (MalformedURLException e) {  
  39.     } catch (IOException e) {  
  40.     }  
  41.  }  
  42. /** 
  43.  *方法说明:显示信息 
  44.  *输入参数: 
  45.  *返回类型: 
  46.  */  
  47.  private void display(String s){  
  48.    if(s!=null)  
  49.      System.out.println(s);  
  50.  }  
  51. }  

  1. package test50;  
  2. import java.io.*;  
  3.   
  4. /** 
  5.  * Title: 客户请求分析 
  6.  * Description: 获取客户的HTTP请求,分析客户所需要的文件 
  7.  * Filename: Request.java 
  8.  */  
  9. public class Request{  
  10.   InputStream in = null;  
  11. /** 
  12.  *方法说明:构造器,获得输入流。这时客户的请求数据。 
  13.  *输入参数: 
  14.  *返回类型: 
  15.  */  
  16.   public Request(InputStream input){  
  17.     this.in = input;  
  18.   }  
  19. /** 
  20.  *方法说明:解析客户的请求 
  21.  *输入参数: 
  22.  *返回类型:String 请求文件字符 
  23.  */  
  24.   public String parse() {  
  25.     //从Socket读取一组数据  
  26.     StringBuffer requestStr = new StringBuffer(2048);  
  27.     int i;  
  28.     byte[] buffer = new byte[2048];  
  29.     try {  
  30.         i = in.read(buffer);  
  31.     }  
  32.     catch (IOException e) {  
  33.         e.printStackTrace();  
  34.         i = -1;  
  35.     }  
  36.     for (int j=0; j<i; j++) {  
  37.         requestStr.append((char) buffer[j]);  
  38.     }  
  39.     System.out.print(requestStr.toString());  
  40.     return getUri(requestStr.toString());  
  41.   }  
  42. /** 
  43.  *方法说明:获取URI字符 
  44.  *输入参数:String requestString 请求字符 
  45.  *返回类型:String URI信息字符 
  46.  */  
  47.   private String getUri(String requestString) {  
  48.     int index1, index2;  
  49.     index1 = requestString.indexOf(' ');  
  50.     if (index1 != -1) {  
  51.         index2 = requestString.indexOf(' ', index1 + 1);  
  52.         if (index2 > index1)  
  53.            return requestString.substring(index1 + 1, index2);  
  54.     }  
  55.     return null;  
  56.   }  
  57. }  

  1. package test50;  
  2. import java.io.*;  
  3.   
  4. /** 
  5.  * Title: 发现HTTP内容和文件内容 
  6.  * Description: 获得用户请求后将用户需要的文件读出,添加上HTTP应答头。发送给客户端。 
  7.  * Filename: Response.java 
  8.  */  
  9. public class Response{  
  10.   OutputStream out = null;  
  11. /** 
  12.  *方法说明:发送信息 
  13.  *输入参数:String ref 请求的文件名 
  14.  *返回类型: 
  15.  */  
  16.   @SuppressWarnings("deprecation")  
  17. public void Send(String ref) throws IOException {  
  18.     byte[] bytes = new byte[2048];  
  19.     FileInputStream fis = null;  
  20.     try {  
  21.         //构造文件  
  22.         File file  = new File(WebServer.WEBROOT, ref);  
  23.         if (file.exists()) {  
  24.             //构造输入文件流  
  25.             fis = new FileInputStream(file);  
  26.             int ch = fis.read(bytes, 02048);  
  27.             //读取文件  
  28.             String sBody = new String(bytes,0);  
  29.             //构造输出信息  
  30.             String sendMessage = "HTTP/1.1 200 OK\r\n" +  
  31.                 "Content-Type: text/html\r\n" +  
  32.                 "Content-Length: "+ch+"\r\n" +  
  33.                 "\r\n" +sBody;  
  34.             //输出文件  
  35.             out.write(sendMessage.getBytes());  
  36.         }else {  
  37.             // 找不到文件  
  38.             String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +  
  39.                 "Content-Type: text/html\r\n" +  
  40.                 "Content-Length: 23\r\n" +  
  41.                 "\r\n" +  
  42.                 "<h1>File Not Found</h1>";  
  43.             out.write(errorMessage.getBytes());  
  44.         }  
  45.          
  46.     }  
  47.     catch (Exception e) {  
  48.         // 如不能实例化File对象,抛出异常。  
  49.         System.out.println(e.toString() );  
  50.     }  
  51.     finally {  
  52.         if (fis != null)  
  53.             fis.close();  
  54.     }  
  55.  }  
  56. /** 
  57.  *方法说明:构造器,获取输出流 
  58.  *输入参数: 
  59.  *返回类型: 
  60.  */  
  61.  public Response(OutputStream output) {  
  62.     this.out = output;  
  63. }  
  64. }  

  1. package test50;  
  2.   
  3. import java.io.*;  
  4. import java.net.*;  
  5.   
  6. /** 
  7.  * Title: WEB服务器 
  8.  * Description: 使用Socket创建一个WEB服务器,本程序是多线程系统以提高反应速度。 
  9.  * Filename: WebServer.java 
  10.  */  
  11. class WebServer  
  12. {  
  13.  public static String WEBROOT = "";//默认目录  
  14.  public static String defaultPage = "index.htm";//默认文件  
  15.  public static void main (String [] args) throws IOException  
  16.  {//使用输入的方式通知服务默认目录位置,可用./root表示。  
  17.    if(args.length!=1){  
  18.      System.out.println("USE: java WebServer ./rootdir");  
  19.      return;  
  20.    }else{  
  21.      WEBROOT = args[0];  
  22.    }  
  23.    System.out.println ("Server starting...\n");   
  24.    //使用8000端口提供服务  
  25.    ServerSocket server = new ServerSocket (8000);  
  26.    while (true)  
  27.    {  
  28.     //阻塞,直到有客户连接  
  29.      Socket sk = server.accept ();  
  30.      System.out.println ("Accepting Connection...\n");  
  31.      //启动服务线程  
  32.      new WebThread (sk).start ();  
  33.    }  
  34.  }  
  35. }  
  36.   
  37. /** 
  38.  * Title: 服务子线程 
  39.  * Description: 使用线程,为多个客户端服务 
  40.  
  41.  * Filename:  
  42.  
  43.  
  44.  */  
  45. class WebThread extends Thread  
  46. {  
  47.  private Socket sk;  
  48.  WebThread (Socket sk)  
  49.  {  
  50.   this.sk = sk;  
  51.  }  
  52. /** 
  53.  *方法说明:线程体 
  54.  *输入参数: 
  55.  *返回类型: 
  56.  */  
  57.  public void run ()  
  58.  {  
  59.   InputStream in = null;  
  60.   OutputStream out = null;  
  61.   try{  
  62.     in = sk.getInputStream();  
  63.     out = sk.getOutputStream();  
  64.       //接收来自客户端的请求。  
  65.       Request rq = new Request(in);  
  66.       //解析客户请求  
  67.       String sURL = rq.parse();  
  68.       System.out.println("sURL="+sURL);  
  69.       if(sURL.equals("/")) sURL = WebServer.defaultPage;  
  70.       Response rp = new Response(out);  
  71.       rp.Send(sURL);        
  72.     }catch (IOException e)  
  73.     {  
  74.        System.out.println (e.toString ());  
  75.     }  
  76.     finally  
  77.     {  
  78.       System.out.println ("Closing Connection...\n");  
  79.       //最后释放资源  
  80.       try{  
  81.        if (in != null)  
  82.          in.close ();  
  83.        if (out != null)  
  84.          out.close ();  
  85.         if (sk != null)  
  86.           sk.close ();  
  87.       }  
  88.       catch (IOException e)  
  89.       {  
  90.       }  
  91.     }  
  92.  }  

抱歉!评论已关闭.