100个Java经典例子(41-50)初学者的利器高手的宝典JavaSE

作者: admin 分类: 学习文档 发布时间: 2011-11-03 23:06

 

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

 

  1. package test43;
  2. import java.net.*;
  3. import java.io.*;
  4. /**
  5.  * Title: 简单服务器服务端
  6.  * Description: 这是一个简单的服务器端程序
  7.  * Filename: SampleServer.java
  8.  */
  9. public class SampleServer {
  10.     public static void main(String[] arges) {
  11.         try {
  12.             int port = 8888;
  13.             // 使用8888端口创建一个ServerSocket
  14.             ServerSocket mySocket = new ServerSocket(port);
  15.             // 等待监听是否有客户端连接
  16.             Socket sk = mySocket.accept();
  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.             System.out.println(“客户端信息:” + in.readLine());
  25.             // 向客户端回信息
  26.             out.println(“你好,我是服务器。我使用的端口号: ” + port);
  27.         } catch (Exception e) {
  28.             System.out.println(e);
  29.         }
  30.     }
  31. }

 

  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.  ServerThread (Socket sk)
  32.  {
  33.   this.sk = sk;
  34.  }
  35. //线程运行实体
  36.  public void run ()
  37.  {
  38.   BufferedReader in = null;
  39.   PrintWriter out = null;
  40.   try{
  41.     InputStreamReader isr;
  42.     isr = new InputStreamReader (sk.getInputStream ());
  43.     in = new BufferedReader (isr);
  44.     out = new PrintWriter (
  45.            new BufferedWriter(
  46.             new OutputStreamWriter(
  47.               sk.getOutputStream ())), true);
  48.     while(true){
  49.       //接收来自客户端的请求,根据不同的命令返回不同的信息。
  50.       String cmd = in.readLine ();
  51.       System.out.println(cmd);
  52.       if (cmd == null)
  53.           break;
  54.       cmd = cmd.toUpperCase ();
  55.       if (cmd.startsWith (“BYE”)){
  56.          out.println (“BYE”);
  57.          break;
  58.       }else{
  59.         out.println (“你好,我是服务器!”);
  60.       }
  61.     }
  62.     }catch (IOException e)
  63.     {
  64.        System.out.println (e.toString ());
  65.     }
  66.     finally
  67.     {
  68.       System.out.println (“Closing Connection…n”);
  69.       //最后释放资源
  70.       try{
  71.        if (in != null)
  72.          in.close ();
  73.        if (out != null)
  74.          out.close ();
  75.         if (sk != null)
  76.           sk.close ();
  77.       }
  78.       catch (IOException e)
  79.       {
  80.         System.out.println(“close err”+e);
  81.       }
  82.     }
  83.  }
  84. }

 

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

 

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

 

  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.      /*–   与POP3服务器握手过程   –*/
  50.       System.out.print (“C:”);
  51.       String cmd = ”user ”+popUser;
  52.       // 将用户名发送到POP3服务程序。
  53.       System.out.println (cmd);
  54.       sockout.println (cmd);
  55.       // 读取POP3服务程序的回应消息。
  56.       String reply = sockin.readLine ();
  57.       System.out.println (“S:” + reply);
  58.       System.out.print (“C:”);
  59.       cmd = ”pass ”;
  60.       // 将密码发送到POP3服务程序。
  61.       System.out.println(cmd+”*********”);
  62.       sockout.println (cmd+popPassword);
  63.       // 读取POP3服务程序的回应消息。
  64.       reply = sockin.readLine ();
  65.       System.out.println (“S:” + reply);
  66.       System.out.print (“C:”);
  67.       cmd = ”stat”;
  68.       // 获取邮件数据。
  69.       System.out.println(cmd);
  70.       sockout.println (cmd);
  71.       // 读取POP3服务程序的回应消息。
  72.       reply = sockin.readLine ();
  73.       System.out.println (“S:” + reply);
  74.       if(reply==null) return;
  75.       System.out.print (“C:”);
  76.       cmd = ”retr 1″;
  77.       // 将接收第一丰邮件命令发送到POP3服务程序。
  78.       System.out.println(cmd);
  79.       sockout.println (cmd);
  80.       // 输入了RETR命令并且返回了成功的回应码,持续从套接字读取输出,
  81.       // 直到遇到<CRLF>.<CRLF>。这时从套接字读出的输出就是邮件的内容。
  82.       if (cmd.toLowerCase ().startsWith (“retr”) &&
  83.         reply.charAt (0) == ’+')
  84.         do
  85.         {
  86.           reply = sockin.readLine ();
  87.           System.out.println (“S:” + reply);
  88.           if (reply != null && reply.length () > 0)
  89.             if (reply.charAt (0) == ’.')
  90.               break;
  91.         }
  92.         while (true);
  93.       cmd = ”quit”;
  94.       // 将命令发送到POP3服务程序。
  95.       System.out.print (cmd);
  96.       sockout.println (cmd);
  97.    }
  98.    catch (IOException e)
  99.    {
  100.      System.out.println (e.toString ());
  101.    }
  102.    finally
  103.    {
  104.      try
  105.      {  if (client != null)
  106.           client.close ();
  107.      }
  108.      catch (IOException e)
  109.      {
  110.      }
  111.    }
  112.   }
  113. }

 

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

 

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

 

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

 

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

 

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

 

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

如果觉得我的文章对您有用,请随意赞赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Protected by WP Anti Spam