• java_Socket网络编程


    1.简单服务器端
    /*
    import java.net.*;
    import java.io.*;
    */
    ServerSocket server=null;
    try {
        server=new ServerSocket(%%1);
    }catch(Exception e){
        System.out.println("不能监听:"+e.toString());
    }
    Socket socket=null;
    try {
        socket=server.accept();
        BufferedReader %%3=new BufferedReader(new InputStreamReader(socket.getInputStream()));
        PrintWriter %%4=new PrintWriter(socket.getOutputStream());
        String %%2=%%3.readLine();
        %%4.println("");
        %%4.flush();
        %%4.close();
        %%3.close();
    }
    catch(IOException e){
        System.out.println("出错:"+e.toString());
    }finally{
        try {
            if(socket!=null){
                socket.close();
                server.close();
            }
        }
        catch(IOException e){
            e.printStackTrace();
        }
    }
    
    2.简单客户端
    /*
    import java.net.*;
    import java.io.*;
    */
    Socket socket=null;
    try {
        socket=new Socket(%%1,%%2);
        PrintWriter %%3=new PrintWriter(socket.getOutputStream());
        BufferedReader %%4 = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        %%3.println("");
        %%3.flush();
        String %%5=%%4.readLine();
        %%6
            %%3.close();
        %%4.close();
    }catch(Exception e){
        e.printStackTrace();
    }
    finally{
        try {
            socket.close();
        }
        catch(IOException e){
            e.printStackTrace();
        }
    }
    
    3.获得本机IP
    //import java.net.*;
    String strIP = null;
    try     
    {     
        strIP =InetAddress.getLocalHost().getHostAddress().toString();   
    }
    catch(UnknownHostException e)
    {
        e.printStackTrace();
    }
    /*
    %%1=InetAddress.getLocalHost().getHostAddress();
    Enumeration<NetworkInterface> netInterfaces = null;   
    try {   
    netInterfaces = NetworkInterface.getNetworkInterfaces();   
    while (netInterfaces.hasMoreElements()) {   
    NetworkInterface ni = netInterfaces.nextElement();   
    System.out.println("DisplayName:" + ni.getDisplayName());   
    System.out.println("Name:" + ni.getName());   
    Enumeration<InetAddress> ips = ni.getInetAddresses();   
    while (ips.hasMoreElements()) {   
    System.out.println("IP:" 
    + ips.nextElement().getHostAddress());   
    }   
    }   
    } catch (Exception e) {   
    e.printStackTrace();   
    }
    */
    
    4.端对端通信
    //import java.net.*;
    byte[] buf=new byte[1024];
    DatagramSocket ds=new DatagramSocket(%%1);
    DatagramPacket ip=new DatagramPacket(buf,buf.length);
    while(true){
        ds.receive(ip);
    }
    InetAddress target=InetAddress.getByName(%%2);
    DatagramSocket ds=new DatagramSocket(%%3);
    String str=%%4;
    byte[] buf=str.getBytes();
    DatagramPacket op=new DatagramPacket(buf,buf.length,target,%%5);
    ds.send(op);
    ds.close();
    
    5.点对点通信
    /*
    import java.io.*;
    import java.net.*;
    */
    public class %%6 extends Thread {
        @Override
            public void run() {
                ServerSocket server = null;
                try {
                    server = new ServerSocket(5000);
                } catch (Exception e) {
                    System.out.println("不能监听:" + e.toString());
                }
                Socket socket = null;
                try {
                    socket = server.accept();
                    BufferedReader req = new BufferedReader(new InputStreamReader(
                        socket.getInputStream()));
                    PrintWriter os = new PrintWriter(socket.getOutputStream());
                    Debug.p(req.readLine());
                    os.println("Server");
                    os.flush();
                    os.close();
                    req.close();
                } catch (IOException e) {
                    System.out.println("出错:" + e.toString());
                } finally {
                    try {
                        if (socket != null) {
                            socket.close();
                            server.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
        }
    
    
        Thread t = new %%6();
        t.start();
        String strIP = null;
        try {
            strIP = InetAddress.getLocalHost().getHostAddress().toString();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        Socket socket = null;
        try {
            socket = new Socket(strIP, 4000);
            PrintWriter pw = new PrintWriter(socket.getOutputStream());
            BufferedReader br = new BufferedReader(new InputStreamReader(socket
                .getInputStream()));
            pw.println("Client");
            pw.flush();
            Debug.p(br.readLine());
            pw.close();
            br.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    6.UDP对时服务器端
    /*
    import java.io.*;
    import java.net.*;
    import java.util.*;
    */
    public class UDPServer extends Thread {
        @Override
            public void run() {
                String strIP = null;
                try {
                    strIP = InetAddress.getLocalHost().toString();
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                }
                DatagramSocket ds;
                try {
                    ds = new DatagramSocket(5000);
                    byte[] buf = new byte[1024];
                    DatagramPacket dpt = new DatagramPacket(buf, buf.length);
                    ds.receive(dpt);
                    String Read_str = new String(buf, 0, dpt.getLength());
                    if (Read_str.equals("TimeNow")) {
                        Date t = new Date();
                        byte[] sendData = String.valueOf("cmd date " +(t.getYear()+1900)+"-"+(t.getMonth()+1)+"-"+t.getDate()+" && time "+t.getHours()+":"+t.getMinutes()+":"+t.getSeconds()).getBytes();
                        DatagramPacket dp = new DatagramPacket(sendData,
                            sendData.length, InetAddress.getLocalHost(), 2000);
                        ds.send(dp);
                    }
                    ds.close();
                } catch (SocketException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }
    
        Thread t = new UDPServer();
        t.start();
    
    }
    
    7.UDP对时客户端
    /*
    import java.io.*;
    import java.net.*;
    */
    String strIP = null;
    try {
        strIP = InetAddress.getLocalHost().getHostAddress().toString();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    }
    byte[] buf = new byte[1024];
    DatagramSocket ds;
    try {
        ds = new DatagramSocket(2000);
        DatagramPacket ip = new DatagramPacket(buf, buf.length);
        InetAddress target = InetAddress.getByName(strIP);
        String sendData = "TimeNow";
        byte[] buffer = sendData.getBytes();
        DatagramPacket op = new DatagramPacket(buffer, buffer.length,
            target, 5000);
        ds.send(op);
        ds.receive(ip);
        /*
        * 当前时间: 15:38:51.12 输入新时间: 当前日期: 2009-05-26 星期二 输入新日期: (年月日)
        */
        try {
            Runtime.getRuntime().exec(new String(buf, 0, ip.getLength()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        ds.close();
    } catch (SocketException e) {
        e.printStackTrace();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    8.点对点传输文件
    /*
    import   java.io.*;
    import   java.net.*;
    import   java.util.*;
    */
    private   HttpURLConnection   connection;//存储连接   
    private   int   downsize   =   -1;//下载文件大小,初始值为-1   
    private   int   downed   =   0;//文加已下载大小,初始值为0   
    private   RandomAccessFile   savefile;//记录下载信息存储文件   
    private   URL   fileurl;//记录要下载文件的地址   
    private   DataInputStream   fileStream;//记录下载的数据流
    try{   
        /*开始创建下载的存储文件,并初始化值*/   
        File   tempfileobject   =   new   File("h:\webwork-2.1.7.zip");   
        if(!tempfileobject.exists()){   
            /*文件不存在则建立*/   
            tempfileobject.createNewFile();   
        }   
        savefile   =   new   RandomAccessFile(tempfileobject,"rw");   
    
        /*建立连接*/   
        fileurl   =   new   URL("https://webwork.dev.java.net/files/documents/693/9723/webwork-2.1.7.zip");   
        connection   =   (HttpURLConnection)fileurl.openConnection();   
        connection.setRequestProperty("Range","byte="+this.downed+"-");   
    
        this.downsize   =   connection.getContentLength();   
        //System.out.println(connection.getContentLength());   
    
        new   Thread(this).start();   
    }   
    catch(Exception   e){   
        System.out.println(e.toString());   
        System.out.println("构建器错误");   
        System.exit(0);   
    }   
    public   void   run(){   
        /*开始下载文件,以下测试非断点续传,下载的文件存在问题*/   
        try{   
            System.out.println("begin!");   
            Date   begintime   =   new   Date();   
            begintime.setTime(new   Date().getTime());   
            byte[]   filebyte;   
            int   onecelen;   
            //System.out.println(this.connection.getInputStream().getClass().getName());   
            this.fileStream   =   new   DataInputStream(   
                new   BufferedInputStream(   
                this.connection.getInputStream()));   
            System.out.println("size   =   "   +   this.downsize);   
            while(this.downsize   !=   this.downed){   
                if(this.downsize   -   this.downed   >   262144){//设置为最大256KB的缓存   
                    filebyte   =   new   byte[262144];   
                    onecelen   =   262144;   
                }   
                else{   
                    filebyte   =   new   byte[this.downsize   -   this.downed];   
                    onecelen   =   this.downsize   -   this.downed;   
                }   
                onecelen   =   this.fileStream.read(filebyte,0,onecelen);   
                this.savefile.write(filebyte,0,onecelen);   
                this.downed   +=   onecelen;   
                System.out.println(this.downed);   
            }   
            this.savefile.close();   
            System.out.println("end!");   
            System.out.println(begintime.getTime());   
            System.out.println(new   Date().getTime());   
            System.out.println(begintime.getTime()   -   new   Date().getTime());   
        }   
        catch(Exception e){   
            System.out.println(e.toString());   
            System.out.println("run()方法有问题!");   
        }
    }
    
    /***
    //FileClient.java
    import java.io.*;
    import java.net.*;
    public class FileClient {
    public static void main(String[] args) throws Exception {
    
    //使用本地文件系统接受网络数据并存为新文件
    
    File file = new File("d:\fmd.doc");
    
    file.createNewFile();
    
    RandomAccessFile raf = new RandomAccessFile(file, "rw");
    
    // 通过Socket连接文件服务器
    
    Socket server = new Socket(InetAddress.getLocalHost(), 3318);
    //创建网络接受流接受服务器文件数据
    InputStream netIn = server.getInputStream();
    InputStream in = new DataInputStream(new BufferedInputStream(netIn));
    //创建缓冲区缓冲网络数据
    
    byte[] buf = new byte[2048];
    
    int num = in.read(buf);
    
    while (num != (-1)) {//是否读完所有数据
    
    raf.write(buf, 0, num);//将数据写往文件
    
    raf.skipBytes(num);//顺序写文件字节
    
    num = in.read(buf);//继续从网络中读取文件
    
    }
    in.close();
    raf.close();
    }
    }
    
    //FileServer.java
    import java.io.*;
    import java.util.*;
    import java.net.*;
    public class FileServer {
    public static void main(String[] args) throws Exception {
    
    //创建文件流用来读取文件中的数据
    
    File file = new File("d:\系统特点.doc");
    
    FileInputStream fos = new FileInputStream(file);
    
    //创建网络服务器接受客户请求
    
    ServerSocket ss = new ServerSocket(8801);
    
    Socket client = ss.accept();
    
    //创建网络输出流并提供数据包装器
    
    OutputStream netOut = client.getOutputStream();
    
    OutputStream doc = new DataOutputStream(
    new BufferedOutputStream(netOut));
    
    //创建文件读取缓冲区
    
    byte[] buf = new byte[2048];
    
    int num = fos.read(buf);
    while (num != (-1)) {//是否读完文件
    doc.write(buf, 0, num);//把文件数据写出网络缓冲区
    doc.flush();//刷新缓冲区把数据写往客户端
    num = fos.read(buf);//继续从文件中读取数据
    }
    fos.close();
    doc.close();
    }
    }
    */
    
    9.发送邮件
    /*
    import java.applet.*;
    import java.awt.*;
    import java.io.*;
    import java.net.*;
    */
    public class WebSendMail extends Applet{ 
        // 初始化界面 
        public void init(){ 
            String s = getParameter("BgColor"); 
            if(s == null) 
                s = "0,0,0"; 
            bgcolor = param.decodeColor(s); 
            String s1 = getParameter("FgColor"); 
            if(s1 == null) 
                s1 = "255,255,255"; 
            fgcolor = param.decodeColor(s1); 
            in_mailto = getParameter("MailTo"); 
            if(in_mailto == null) 
                in_mailto = ""; 
            in_website = getParameter("Website"); 
            if(in_website == null) 
                in_website = ""; 
            d = size(); 
            SuperCedeInit(); 
        } 
        public void sendMsg() { // 处理消息发送 
            try { 
                button_Send.disable(); 
                button_Clear.disable(); 
                host = getCodeBase().getHost(); 
                if(host.length() == 0) 
                    host = "localhost"; 
                textArea_Log.appendText("Connecting. '" + host + "'
    "); 
                Socket socket = new Socket(host, 25); 
                textArea_Log.appendText("Connect OK '" + host + "'
    "); 
                // 创建输入输出流 
                DataOutputStream dataoutputstream = new DataOutputStream(socket.getOutputStream()); 
                DataInputStream datainputstream = new DataInputStream(socket.getInputStream()); 
                textArea_Log.appendText("Send Start '" + textField_Subject.getText() + "'
    "); 
                textArea_Log.appendText(datainputstream.readLine() + "
    "); 
                dataoutputstream.writeBytes("HELO " + host + "
    "); 
                textArea_Log.appendText(datainputstream.readLine() + "
    "); 
                dataoutputstream.writeBytes("MAIL FROM: " + textField_From.getText() + "
    "); 
                textArea_Log.appendText(datainputstream.readLine() + "
    "); 
                dataoutputstream.writeBytes("RCPT TO: " + textField_To.getText() + "
    "); 
                textArea_Log.appendText(datainputstream.readLine() + "
    "); 
                dataoutputstream.writeBytes("DATA
    "); 
                textArea_Log.appendText(datainputstream.readLine() + "
    "); 
                dataoutputstream.writeBytes("X-Mailer: WebSendMail
    "); 
                dataoutputstream.writeBytes("X-WebSite: " + in_website + "
    "); 
                dataoutputstream.writeBytes("Subject: " + textField_Subject.getText() + "
    " + 
                    textArea_Msg.getText() + "
    "); 
                dataoutputstream.writeBytes(".
    QUIT
    "); 
                textArea_Log.appendText(datainputstream.readLine() + "
    ------------------------------
    "); 
                socket.close(); 
                button_Send.enable(); 
                button_Clear.enable(); 
                button_Send.enable(); 
                button_Clear.enable(); 
                return; 
            } 
            catch(UnknownHostException _ex) { 
                // 处理连接异常 
                textArea_Log.appendText("Connect Error '" + host + "'
    "); 
                return; 
            } 
            catch(IOException _ex) { 
                button_Send.enable(); 
            } 
            button_Clear.enable(); 
            textArea_Log.appendText("Send Error '" + textField_Subject.getText() + "'
    "); 
        } 
        public void paint(Graphics g){} 
        protected void Button_SendClicked(Event event) { 
            // 处理发送按钮点击事件 
            if(textField_From.getText().length() == 0){ 
                // 如果信件来源为空 
                textArea_Log.appendText("Input? 'From'
    "); 
                return; 
            } 
            if(textField_To.getText().length() == 0) { 
                // 如果信件目的地为空 
                textArea_Log.appendText("Input? 'To'
    "); 
                return; 
            } 
            if(textField_Subject.getText().length() == 0){ 
                // 如果信件主题为空 
                textArea_Log.appendText("Input? 'Subject'
    "); 
                return; 
            } 
            if(textArea_Msg.getText().length() == 0) { 
                // 如果信件内容为空 
                textArea_Log.appendText("Input? 'Message'
    "); 
                return; 
            } 
            else { 
                sendMsg(); 
                return; 
            } 
        } 
        protected void Button_ClearClicked(Event event) {// 清除按钮点击处理,清空所有已填内容 
            textField_Subject.setText(""); 
            textField_From.setText(""); 
            textField_To.setText(in_mailto); 
            textArea_Msg.setText(""); 
        } 
        protected void Button_ClearLogClicked(Event event) { 
            // 清空日志 
            textArea_Log.setText(""); 
        } 
        // 调用或重载超类相关方法实现初始化、开始、结束以及事件处理等 
        public boolean handleEvent(Event event) { 
            return SuperCedeEvent(event); 
        } 
        public void start() { 
            SuperCedeStart(); 
        } 
        public void stop() { 
            SuperCedeStop(); 
        } 
        public String getAppletInfo() { 
            return "WebSendMail"; 
        } 
        private final void SuperCedeInit() { 
            // 详细的界面设置 
            setLayout(null); 
            setForeground(fgcolor); 
            setBackground(bgcolor); 
            addNotify(); 
            resize(d.width, d.height); 
            label4 = new Label("From :", 2); 
            label4.setForeground(fgcolor); 
            add(label4); 
            int i = insets().left; 
            label4.reshape(i, insets().top, 50, 22); 
            textField_From = new TextField(""); 
            textField_From.setEditable(true); 
            textField_From.setForeground(new Color(0, 0, 0)); 
            textField_From.setBackground(new Color(255, 255, 255)); 
            add(textField_From); 
            int j = insets().left + 50; 
            textField_From.reshape(j, insets().top, d.width - 50, 22); 
            label3 = new Label("To :", 2); 
            label3.setForeground(fgcolor); 
            add(label3); 
            int k = insets().left; 
            label3.reshape(k, insets().top + 22, 50, 22); 
            textField_To = new TextField(in_mailto); 
            textField_To.setEditable(true); 
            textField_To.setForeground(new Color(0, 0, 0)); 
            textField_To.setBackground(new Color(255, 255, 255)); 
            add(textField_To); 
            int l = insets().left + 50; 
            textField_To.reshape(l, insets().top + 22, d.width - 50, 22); 
            label_Subject = new Label("Subject :", 2); 
            label_Subject.setForeground(fgcolor); 
            add(label_Subject); 
            label_Subject.reshape(0, insets().top + 44, 50, 22); 
            textField_Subject = new TextField(""); 
            textField_Subject.setEditable(true); 
            textField_Subject.setForeground(new Color(0, 0, 0)); 
            textField_Subject.setBackground(new Color(255, 255, 255)); 
            add(textField_Subject); 
            int i1 = insets().left + 50; 
            textField_Subject.reshape(i1, insets().top + 44, d.width - 50, 22); 
            textArea_Msg = new TextArea(""); 
            textArea_Msg.setEditable(true); 
            textArea_Msg.setForeground(new Color(0, 0, 0)); 
            textArea_Msg.setBackground(new Color(255, 255, 255)); 
            add(textArea_Msg); 
            textArea_Msg.reshape(0, insets().top + 66, d.width, d.height - 170); 
            textArea_Log = new TextArea(""); 
            textArea_Log.setEditable(true); 
            textArea_Log.setForeground(new Color(0, 0, 0)); 
            textArea_Log.setBackground(new Color(192, 192, 192)); 
            add(textArea_Log); 
            textArea_Log.reshape(0, d.height - 105, d.width, 80); 
            button_Send = new Button("Send"); 
            button_Send.setForeground(new Color(128, 0, 0)); 
            button_Send.setBackground(new Color(192, 192, 192)); 
            add(button_Send); 
            button_Send.reshape(d.width / 2 - 105, d.height - 25, 70, 25); 
            button_Clear = new Button("Clear"); 
            button_Clear.setForeground(new Color(0, 128, 0)); 
            button_Clear.setBackground(new Color(192, 192, 192)); 
            add(button_Clear); 
            button_Clear.reshape(d.width / 2 - 35, d.height - 25, 70, 25); 
            button_ClearLog = new Button("Clear Log"); 
            button_ClearLog.setForeground(new Color(0, 0, 128)); 
            button_ClearLog.setBackground(new Color(192, 192, 192)); 
            add(button_ClearLog); 
            button_ClearLog.reshape(d.width / 2 + 35, d.height - 25, 70, 25); 
            super.init(); 
        } 
        private final boolean SuperCedeEvent(Event event) { 
            if(event.target == button_Send && event.id == 1001) { 
                Button_SendClicked(event); 
                return true; 
            } 
            if(event.target == button_Clear && event.id == 1001) { 
                Button_ClearClicked(event); 
                return true; 
            } 
            if(event.target != button_ClearLog || event.id != 1001) { 
                return super.handleEvent(event); 
            } 
            else { 
                Button_ClearLogClicked(event); 
                return true; 
            } 
        } 
        private final void SuperCedeStart(){} 
        private final void SuperCedeStop() {} 
        public WebSendMail() { // 发送邮件 
            param = new CommonApplet(); 
            in_mailto = null; 
        } 
        // 成员变量 
        Color fgcolor; 
        Color bgcolor; 
        String host; 
        Dimension d; 
        CommonApplet param; 
        String in_mailto; 
        String in_website; 
        Button button_Send; 
        Label label_Subject; 
        Label label3; 
        TextField textField_Subject; 
        TextField textField_From; 
        TextField textField_To; 
        TextArea textArea_Msg; 
        Button button_Clear; 
        Button button_ClearLog; 
        Label label4; 
        TextArea textArea_Log; 
    }
    
    10.接收邮件
    //activation.jar
    // http://d.download.csdn.net/down/398258/dbhunter
    //mail.jar
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    
    public class PraseMimeMessage{
        private MimeMessage mimeMessage = null;
        private String saveAttachPath = "";          //附件下载后的存放目录
        private StringBuffer bodytext = new StringBuffer();
        //存放邮件内容的StringBuffer对象
        private String dateformat = "yy-MM-dd HH:mm";    //默认的日前显示格式
    
        /**
        * 构造函数,初始化一个MimeMessage对象
        */
        public PraseMimeMessage(){}
        public PraseMimeMessage(MimeMessage mimeMessage){
            this.mimeMessage = mimeMessage;
            System.out.println("create a PraseMimeMessage object........");
        }
    
        public void setMimeMessage(MimeMessage mimeMessage){
            this.mimeMessage = mimeMessage;
        }
    
        /**
        * 获得发件人的地址和姓名
        */
        public String getFrom()throws Exception{
            InternetAddress address[] = (InternetAddress[])mimeMessage.getFrom();
            String from = address[0].getAddress();
            if(from == null) from="";
            String personal = address[0].getPersonal();
            if(personal == null) personal="";
            String fromaddr = personal+"<"+from+">";
            return fromaddr;
        }
        /**
        * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同
        * "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
        */
    
        public String getMailAddress(String type)throws Exception{
            String mailaddr = "";
            String addtype = type.toUpperCase();
            InternetAddress []address = null;
            if(addtype.equals("TO") || addtype.equals("CC") ||addtype.equals("BCC")){
                if(addtype.equals("TO")){
                    address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.TO);
                }else if(addtype.equals("CC")){
                    address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.CC);
                }else{
                    address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.BCC);
                }
                if(address != null){
                    for(int i=0;i<address.length;i++){
                        String email=address[i].getAddress();
                        if(email==null) email="";
                        else{
                            email=MimeUtility.decodeText(email);
                        }
                        String personal=address[i].getPersonal();
                        if(personal==null) personal="";
                        else{
                            personal=MimeUtility.decodeText(personal);
                        }
                        String compositeto=personal+"<"+email+">";
                        mailaddr+=","+compositeto;
                    }
                    mailaddr=mailaddr.substring(1);
                }
            }else{
                throw new Exception("Error emailaddr type!");
            }
            return mailaddr;
        }
    
        /**
        * 获得邮件主题
        */
    
        public String getSubject()throws MessagingException{
            String subject = "";
            try{
                subject = MimeUtility.decodeText(mimeMessage.getSubject());
                if(subject == null) subject="";
            }catch(Exception exce){
            }
            return subject;
        }
    
        /**
        * 获得邮件发送日期
        */
    
        public String getSentDate()throws Exception{
            Date sentdate = mimeMessage.getSentDate();
            SimpleDateFormat format = new SimpleDateFormat(dateformat);
            return format.format(sentdate);
        }
    
        /**
        * 获得邮件正文内容
        */
    
        public String getBodyText(){
            return bodytext.toString();
        }
    
        /**
        * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件
        * 主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
        */
    
        public void getMailContent(Part part)throws Exception{
            String contenttype = part.getContentType();
            int nameindex = contenttype.indexOf("name");
            boolean conname =false;
            if(nameindex != -1) conname=true;
            System.out.println("CONTENTTYPE: "+contenttype);
            if(part.isMimeType("text/plain") && !conname){
                bodytext.append((String)part.getContent());
            }else if(part.isMimeType("text/html") && !conname){
                bodytext.append((String)part.getContent());
            }else if(part.isMimeType("multipart/*")){
                Multipart multipart = (Multipart)part.getContent();
                int counts = multipart.getCount();
                for(int i=0;i<counts;i++){
                    getMailContent(multipart.getBodyPart(i));
                }
            }else if(part.isMimeType("message/rfc822")){
                getMailContent((Part)part.getContent());
            }else{}
        }
    
        /**
        * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
        */
        public boolean getReplySign()throws MessagingException{
            boolean replysign = false;
            String needreply[] = mimeMessage.getHeader("Disposition-Notification-To");
            if(needreply != null){
                replysign = true;
            }
            return replysign;
        }
    
        /**
        * 获得此邮件的Message-ID
        */
        public String getMessageId()throws MessagingException{
            return mimeMessage.getMessageID();
        }
    
        /**
        * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】
        */
        public boolean isNew()throws MessagingException{
            boolean isnew = false;
            Flags flags = ((Message)mimeMessage).getFlags();
            Flags.Flag []flag = flags.getSystemFlags();
            System.out.println("flags's length: "+flag.length);
            for(int i=0;i<flag.length;i++){
                if(flag[i] == Flags.Flag.SEEN){
                    isnew=true;
                    System.out.println("seen Message.......");
                    break;
                }
            }
            return isnew;
        }
    
        /**
        * 判断此邮件是否包含附件
        */
        public boolean isContainAttach(Part part)throws Exception{
            boolean attachflag = false;
            String contentType = part.getContentType();
            if(part.isMimeType("multipart/*")){
                Multipart mp = (Multipart)part.getContent();
                for(int i=0;i<mp.getCount();i++){
                    BodyPart mpart = mp.getBodyPart(i);
                    String disposition = mpart.getDisposition();
                    if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE))))
                        attachflag = true;
                    else if(mpart.isMimeType("multipart/*")){
                        attachflag = isContainAttach((Part)mpart);
                    }else{
                        String contype = mpart.getContentType();
                        if(contype.toLowerCase().indexOf("application") != -1) attachflag=true;
                        if(contype.toLowerCase().indexOf("name") != -1) attachflag=true;
                    }
                }
            }else if(part.isMimeType("message/rfc822")){
                attachflag = isContainAttach((Part)part.getContent());
            }
            return attachflag;
        }
    
        /**
        * 【保存附件】
        */
    
        public void saveAttachMent(Part part)throws Exception{
            String fileName = "";
            if(part.isMimeType("multipart/*")){
                Multipart mp = (Multipart)part.getContent();
                for(int i=0;i<mp.getCount();i++){
                    BodyPart mpart = mp.getBodyPart(i);
                    String disposition = mpart.getDisposition();
                    if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE)))){
                        fileName = mpart.getFileName();
                        if(fileName.toLowerCase().indexOf("gb2312") != -1){
                            fileName = MimeUtility.decodeText(fileName);
                        }
                        saveFile(fileName,mpart.getInputStream());
                    }else if(mpart.isMimeType("multipart/*")){
                        saveAttachMent(mpart);
                    }else{
                        fileName = mpart.getFileName();
                        if((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") != -1)){
                            fileName=MimeUtility.decodeText(fileName);
                            saveFile(fileName,mpart.getInputStream());
                        }
                    }
                }
            }else if(part.isMimeType("message/rfc822")){
                saveAttachMent((Part)part.getContent());
            }
        }
    
        /**
        * 【设置附件存放路径】
        */
    
        public void setAttachPath(String attachpath){
            this.saveAttachPath = attachpath;
        }
    
        /**
        * 【设置日期显示格式】
        */
    
        public void setDateFormat(String format)throws Exception{
            this.dateformat = format;
        }
    
        /**
        * 【获得附件存放路径】
        */
    
        public String getAttachPath(){
            return saveAttachPath;
        }
    
        /**
        * 【真正的保存附件到指定目录里】
        */
    
        private void saveFile(String fileName,InputStream in)throws Exception{
            String osName = System.getProperty("os.name");
            String storedir = getAttachPath();
            String separator = "";
            if(osName == null) osName="";
            if(osName.toLowerCase().indexOf("win") != -1){
                separator = "\"
                    if(storedir == null || storedir.equals("")) storedir="c:\tmp";
            }else{
                separator = "/";
                storedir = "/tmp";
            }
            File storefile = new File(storedir+separator+fileName);
            System.out.println("storefile's path: "+storefile.toString());
            //for(int i=0;storefile.exists();i++){
            //storefile = new File(storedir+separator+fileName+i);
            //}
            BufferedOutputStream bos = null;
            BufferedInputStream bis = null;
    
            try{
                bos = new BufferedOutputStream(new FileOutputStream(storefile));
                bis = new BufferedInputStream(in);
                int c;
                while((c=bis.read()) != -1){
                    bos.write(c);
                    bos.flush();
                }
            }catch(Exception exception){
                exception.printStackTrace();
                throw new Exception("文件保存失败!");
            }finally{
                bos.close();
                bis.close();
            }
        }
    
        /**
        * PraseMimeMessage类测试
        */
    
        public static void main(String args[])throws Exception{
            String host = "主机名/ip";     //【pop.mail.yahoo.com.cn】
            String username ="用户名";     //【wwp_1124】
            String password ="密码";       //【........】
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("pop3");
            store.connect(host, username, password);
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message message[] = folder.getMessages();
            System.out.println("Messages's length: "+message.length);
            PraseMimeMessage pmm = null;
            for(int i=0;i<message.length;i++){
                pmm = new PraseMimeMessage((MimeMessage)message[i]);
                System.out.println("Message "+i+" subject: "+pmm.getSubject());
                System.out.println("Message "+i+" sentdate: "+pmm.getSentDate());
                System.out.println("Message "+i+" replysign: "+pmm.getReplySign());
                System.out.println("Message "+i+" hasRead: "+pmm.isNew());
                System.out.println("Message "+i+" containAttachment: "+pmm.isContainAttach((Part)message[i]));
                System.out.println("Message "+i+" form: "+pmm.getFrom());
                System.out.println("Message "+i+" to: "+pmm.getMailAddress("to"));
                System.out.println("Message "+i+" cc: "+pmm.getMailAddress("cc"));
                System.out.println("Message "+i+" bcc: "+pmm.getMailAddress("bcc"));
                pmm.setDateFormat("yy年MM月dd日 HH:mm");
                System.out.println("Message "+i+" sentdate: "+pmm.getSentDate());
                System.out.println("Message "+i+" Message-ID: "+pmm.getMessageId());
                pmm.getMailContent((Part)message[i]);
                System.out.println("Message "+i+" bodycontent: 
    "+pmm.getBodyText());
                pmm.setAttachPath("c:\tmp\coffeecat1124");
                pmm.saveAttachMent((Part)message[i]);
            }
        }
    }
    
    11.多线程阻塞通信
    
    12.多线程非阻塞通信
    
    13.多线程文件断点续传
    
    14.多线程多文件断点续传
    
    15.截取屏幕
    import java.awt.*;
    import java.awt.image.*;
    import java.io.File;
    import java.io.IOException;
    import javax.imageio.ImageIO;
    import javax.swing.*;
    import java.sql.*;
    /** *//*******************************************************************
          * 该JavaBean可以直接在其他Java应用程序中调用,实现屏幕的"拍照"
          * This JavaBean is used to snapshot the GUI in a
          * Java application! You can embeded
          * it in to your java application source code, and us
          * it to snapshot the right GUI of the application
          * @see javax.ImageIO
          * @author liluqun ([email]liluqun@263.net[/email])
          * @version 1.0
          *
          *****************************************************/
    public class GuiCamera ...{
        private String fileName; //文件的前缀
    
        private String defaultName = "GuiCamera";
    
        static int serialNum = 0;
    
        private String imageFormat; //图像文件的格式
    
        private String defaultImageFormat = "jpg";
    
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    
        /** *//****************************************************************
              * 默认的文件前缀为GuiCamera,文件格式为PNG格式
              * The default construct will use the default
              * Image file surname "GuiCamera",
              * and default image format "png"
              ****************************************************************/
        public GuiCamera() ...{
            fileName = defaultName;
            imageFormat = defaultImageFormat;
    
        }
    
        /** *//****************************************************************
              * @param s the surname of the snapshot file
              * @param format the format of the  image file,
              * it can be "jpg" or "png"
              * 本构造支持JPG和PNG文件的存储
              ****************************************************************/
        public GuiCamera(String s, String format) ...{
    
            fileName = s;
            imageFormat = format;
        }
    
        /** *//****************************************************************
              * 对屏幕进行拍照
              * snapShot the Gui once
              ****************************************************************/
        public void snapShot() ...{
    
            try ...{
                //拷贝屏幕到一个BufferedImage对象screenshot
                BufferedImage screenshot = (new Robot())
                    .createScreenCapture(new Rectangle(0, 0,
                    (int) d.getWidth(), (int) d.getHeight()));
                serialNum++;
                //根据文件前缀变量和文件格式变量,自动生成文件名
                String name = fileName + String.valueOf(serialNum) + "."
                    + imageFormat;
                File f = new File(name);
                System.out.print("Save File " + name);
                //将screenshot对象写入图像文件
                ImageIO.write(screenshot, imageFormat, f);
                System.out.print("..Finished! ");
            } catch (Exception ex) ...{
                System.out.println(ex);
            }
        }
    
        public static void main(String[] args) ...{
            System.out.print("打开连接");
            GuiCamera cam = new GuiCamera("d:Hello", "jpg");//
    
            cam.snapShot();
        }
    }
    
    16.聊天室服务器端逻辑
    //Debug.java
    import java.util.*;
    
    public class Debug {
        public static String p(String s) {
            System.out.println(s);
            return s;
        }
    
        public static Object p(Object O) {
            System.out.println(O.toString());
            return O;
        }
    
        public static Object[] p(Object[] O) {
            System.out.print("[");
            String s = "";
            for (Object o : O) {
                System.out.print(s);
                System.out.print(o.toString());
                s = ",";
            }
            System.out.println("]");
            return O;
        }
    
        public static boolean p(boolean b) {
            System.out.println(b);
            return b;
        }
    
        public static int p(int i) {
            System.out.println(i);
            return i;
        }
    
        public static long p(long i) {
            System.out.println(i);
            return i;
        }
    
        @SuppressWarnings("unchecked")
            public static Map.Entry p(Map.Entry l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static HashSet p(HashSet l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static HashMap p(HashMap l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static Map p(Map l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static LinkedHashSet p(LinkedHashSet l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static TreeSet p(TreeSet l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static Set p(Set l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static ArrayList p(ArrayList l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static LinkedList p(LinkedList l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static List p(List l) {
                System.out.println(l);
                return l;
        }
    }
    
    //Service.java
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class Service extends Thread{
        private Socket client=null;
        private Server server=null;
        public Service(Server server,Socket client){
            this.server=server;
            this.client=client;
        }
        public void run(){
            try {
                BufferedReader br=new BufferedReader(new InputStreamReader(client.getInputStream()));
                while(true){
                    String str=br.readLine();
                    List<Socket> li=server.getLi();
                    for(Socket c:li){
                        if(!c.isClosed() && c.isConnected()){
                            OutputStream os=c.getOutputStream();
                            os.write((str+"
    ").getBytes());
                        }else{
                            client.close();
                            server.getLi().remove(client);
                            break;
                        }
                    }
                }
            }catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    //Server.java
    import java.util.*;
    import java.io.*;
    import java.net.*;
    public class Server {
        private List<Socket> li=new ArrayList<Socket>();
        private ServerSocket ss=null;
        public List<Socket> getLi(){
            return li;
        }
        public Server(int port){
            try {
                ss=new ServerSocket(port);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        public void start(){
            while(true){
                Socket s;
                try {
                    s = ss.accept();
                    li.add(s);
                    new Service(this,s).start();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public static void main(String[] args) {
            new Server(8888).start();
        }
    }
    
    17.聊天室客户端逻辑
    //Debug.java
    import java.util.*;
    public class Debug {
        public static String p(String s) {
            System.out.println(s);
            return s;
        }
    
        public static Object p(Object O) {
            System.out.println(O.toString());
            return O;
        }
    
        public static Object[] p(Object[] O) {
            System.out.print("[");
            String s = "";
            for (Object o : O) {
                System.out.print(s);
                System.out.print(o.toString());
                s = ",";
            }
            System.out.println("]");
            return O;
        }
    
        public static boolean p(boolean b) {
            System.out.println(b);
            return b;
        }
    
        public static int p(int i) {
            System.out.println(i);
            return i;
        }
    
        public static long p(long i) {
            System.out.println(i);
            return i;
        }
    
        @SuppressWarnings("unchecked")
            public static Map.Entry p(Map.Entry l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static HashSet p(HashSet l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static HashMap p(HashMap l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static Map p(Map l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static LinkedHashSet p(LinkedHashSet l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static TreeSet p(TreeSet l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static Set p(Set l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static ArrayList p(ArrayList l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static LinkedList p(LinkedList l) {
                System.out.println(l);
                return l;
        }
    
        @SuppressWarnings("unchecked")
            public static List p(List l) {
                System.out.println(l);
                return l;
        }
    }
    
    //GetMessage.java
    import javax.swing.*;
    import java.io.*;
    import java.net.*;
    public class GetMessage extends Thread{
        private JTextArea context=null;
        private Socket s=null;
        public GetMessage(JTextArea context,Socket s){
            this.context=context;
            this.s=s;
        }
        public void run(){
            try {
                BufferedReader br=new BufferedReader(new InputStreamReader(s.getInputStream()));
                while(true){
                    String str=br.readLine();
                    String c=context.getText();
                    context.setText(c+"
    "+str);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    //Client.java
    package t3;
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.net.*;
    public class Client extends JFrame {
        private static final long serialVersionUID = 1L;
        private String ip = "";
        private int port = 0;
        public String getIp() {
            return ip;
        }
        public void setIp(String ip) {
            this.ip = ip;
        }
        public int getPort() {
            return port;
        }
        public void setPort(int port) {
            this.port = port;
        }
        private Socket s = null;
        private JTextArea context = new JTextArea(10, 10);
        JScrollPane sp = new JScrollPane(context);
        private JTextField say = new JTextField(10);
        private Container c;
        public Client() {
            c = this.getContentPane();
            c.setLayout(new BorderLayout());
            context.setEditable(false);
            c.add(sp);
            JPanel p = new JPanel();
            p.add(BorderLayout.CENTER, say);
            c.add(BorderLayout.SOUTH, p);
            try {
                s = new Socket(this.ip, this.port);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            say.addActionListener(new ActionListener() {
                private void send(String str) {
                    try {
                        OutputStream os = s.getOutputStream();
                        os.write(str.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
    
                public void actionPerformed(ActionEvent arg0) {
                    String str = say.getText();
                    send(str + "
    ");
                    say.setText("");
                }
            });
            new GetMessage(context, s).start();
            this.setSize(300, 300);
            this.setVisible(true);
            this.setResizable(false);
        }
        public Client(String ip, int port) {
            c = this.getContentPane();
            c.setLayout(new BorderLayout());
            context.setEditable(false);
            c.add(sp);
            JPanel p = new JPanel();
            p.add(BorderLayout.CENTER, say);
            c.add(BorderLayout.SOUTH, p);
            try {
                s = new Socket(ip, port);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            say.addActionListener(new ActionListener() {
                private void send(String str) {
                    try {
                        OutputStream os = s.getOutputStream();
                        os.write(str.getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                public void actionPerformed(ActionEvent arg0) {
                    String str = say.getText();
                    send(str + "
    ");
                    say.setText("");
                }
            });
            new GetMessage(context, s).start();
            this.setSize(300, 300);
            this.setVisible(true);
            this.setResizable(false);
        }
        public static void main(String[] args) {
            String strIP = null;
            try {
                strIP = InetAddress.getLocalHost().getHostAddress().toString();
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            new Client(strIP, 8888); // "127.0.0.1"
        }
    }
    
    18.克隆对象
    class  Student implements Cloneable{
        String name;
        int age;
        protected Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
        public boolean equals(Object s) {
            Student s1=(Student)s;
            if(this.name.equals(s1.name)&&this.age==s1.age)
                return true;
            else 
                return false;
        }
        public Student() {}
        public Student(String name, int age) {
            this.name = name;
            this.age = age;
        }    
    }
    //throws CloneNotSupportedException {
    Student s1=new Student("张三",20);
    Student s2=(Student)s1.clone();
    if(s1==s2){
        System.out.println("s1 and s2 are same object!");
    }else{
        System.out.println("s1 and s2 are NOT same object!");
    }
    if(s1.equals(s2)){
        System.out.println("s1 and s2 are equals!");
    }else{
        System.out.println("s1 and s2 are NOT equals!");
    }
    
    19.XML属性文件解析
    /*
    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    throws ParserConfigurationException, SAXException, IOException {
    */
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    DocumentBuilder db=dbf.newDocumentBuilder();
    Document doc=db.parse(%%1); //"mybook.xml"
    doc.normalize();
    NodeList nl=doc.getElementsByTagName("book");
    for(int i=0;i<nl.getLength();i++){
        Element e=(Element)nl.item(i);
        String title=e.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
        String author=e.getElementsByTagName("author").item(0).getFirstChild().getNodeValue();
        String price=e.getElementsByTagName("price").item(0).getFirstChild().getNodeValue();
        System.out.println("title:"+title);
        System.out.println("author:"+author);
        System.out.println("price:"+price);
    }
    <!-- 
    读取XML配置文件
    /*
    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    */
    try {
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db;
        db = dbf.newDocumentBuilder();
        Document doc;
        doc = db.parse("config.xml");
        doc.normalize();
        NodeList nl = doc.getElementsByTagName("book");
        for (int i = 0; i < nl.getLength(); i++) {
            Element e = (Element) nl.item(i);
            String strurl = e.getElementsByTagName("dbsource").item(0)
                .getFirstChild().getNodeValue();
            String username;
            if (e.getElementsByTagName("username").item(0).getFirstChild() == null) {
                username = "";
            } else {
                username = e.getElementsByTagName("username").item(0)
                    .getFirstChild().getNodeValue();
            }
            String password;
            if (e.getElementsByTagName("username").item(0).getFirstChild() == null) {
                password = "";
            } else {
                password = e.getElementsByTagName("password").item(0)
                    .getFirstChild().getNodeValue();
            }
            // strurl
            // username
            // password
        }
    } catch (ParserConfigurationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (SAXException e2) {
        // TODO Auto-generated catch block
        e2.printStackTrace();
    } catch (IOException e3) {
        // TODO Auto-generated catch block
        e3.printStackTrace();
    }
    -->
    
    20.XML属性文件构造
    /*
    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    throws ParserConfigurationException, SAXException, IOException {
    */
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    DocumentBuilder db=dbf.newDocumentBuilder();
    Document doc=db.parse(%%1); //"mybook.xml"
    doc.normalize();
    NodeList nl=doc.getElementsByTagName("book");
    for(int i=0;i<nl.getLength();i++){
        Element e=(Element)nl.item(i);
        String title=e.getElementsByTagName("title").item(0).getFirstChild().getNodeValue();
        String author=e.getElementsByTagName("author").item(0).getFirstChild().getNodeValue();
        String price=e.getElementsByTagName("price").item(0).getFirstChild().getNodeValue();
        System.out.println("title:"+title);
        System.out.println("author:"+author);
        System.out.println("price:"+price);
    }
    
    21.XML文件节点遍历操作
    /*
    import java.io.*;
    import javax.xml.parsers.*;
    import org.w3c.dom.*;
    import org.xml.sax.*;
    */
    private DocumentBuilderFactory factory = DocumentBuilderFactory
    .newInstance();
    private DocumentBuilder builder;
    private Document doc;
    private Element element;
    
    public Dead() {
        try {
            builder = factory.newDocumentBuilder();
            doc = builder.parse("Produces.xml");
            element = doc.getDocumentElement();
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public void findAll(NodeList lin) {
        for (int i = 0; i < lin.getLength(); i++) {
            Node node = lin.item(i);
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                System.out.println(node.getNodeName());
                if (!node.getFirstChild().getNodeValue().trim().equals("")) {
                    System.out.println(node.getFirstChild().getNodeValue());
                }
            }
            NamedNodeMap atts = node.getAttributes();
            if (atts != null) {
                for (int j = 0; j < atts.getLength(); j++) {
                    Node attNode = atts.item(j);
                    if (attNode.getNodeType() == Node.ATTRIBUTE_NODE) {
                        System.out.println(attNode.getNodeName() + ":"
                            + attNode.getNodeValue());// 循环某个节点下的所有属性
                    }
                }
            }
            findAll(node.getChildNodes());
        }
    }
    
    NodeList lin = element.getChildNodes();
    this.findAll(lin);
    
    22.XML文件节点遍历查找
    /*
    import java.io.*;
    import javax.xml.parsers.*;
    import org.xml.sax.*;
    import org.xml.sax.helpers.*;
    */
    public class sax extends DefaultHandler{
        String str;
        public sax() {
            super();
        }
        public void startDocument() throws SAXException {
            System.out.println("商品列表");
        }
        //名称空间,本地名称,标签名称(没有名空的话有值),
        public void startElement(String arg0, String arg1, String arg2,
            Attributes arg3) throws SAXException {
                if(arg2.equals("product")){
                    System.out.println(arg3.getValue(0));
                }
        }
        //遇到内容时触发
        public void characters(char[] arg0, int arg1, int arg2) throws SAXException {
            str=new String(arg0,arg1,arg2);
        }
        //结束
        public void endElement(String arg0, String arg1, String arg2)
            throws SAXException {
                if(arg2.equals("name")){
                    System.out.println("name:"+str);
                }else if(arg2.equals("authar")){
                    System.out.println("authar:"+str);
                }else if(arg2.equals("price")){
                    System.out.println("price:"+str);
                }
        }
        public static void main(String[] args) {
            SAXParserFactory factory=SAXParserFactory.newInstance();
            try {
                javax.xml.parsers.SAXParser parser=factory.newSAXParser();
                sax a3=new sax();
                parser.parse(new InputSource(%%1),a3); //"bin/preducts.xml"
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    23.多线程端口监听
    /*
    import java.io.*;
    import java.net.*;
    import java.util.regex.*;
    import com.sun.net.httpserver.*;
    import com.sun.net.httpserver.spi.*;
    */
    public class HTTPDownloadService {
        /**
        * @param args
        * @throws IOException
        */1.  public static void main(String[] args) throws IOException {
            HttpServerProvider httpServerProvider = HttpServerProvider.provider();
            int port = 60080;
            if (args.length > 0) {
                try {
                    port = Integer.parseInt(args[0]);
                } catch (Exception ex) {}
            }
            // 绑定端口1.    InetSocketAddress addr = new InetSocketAddress(port);
            HttpServer httpServer = httpServerProvider.createHttpServer(addr, 1);
            httpServer.createContext("/", new HTTPDownloaderServiceHandler());
            httpServer.setExecutor(null);
            httpServer.start();
            System.out.println("started");
    }
    }
    /**
    * 下载的服务器
    * 
    * @author 赵学庆 www.java2000.net
    */class HTTPDownloaderServiceHandler implements HttpHandler {
        private static Pattern p = Pattern.compile("\?page=(.*?)\&rpage=(.*?)&savepath=(.*)$");
        public void handle(HttpExchange httpExchange) {
            try {
                Matcher m = p.matcher(httpExchange.getRequestURI().toString());
                String response = "OK";
                if (m.find()) {
                    try {
                        new HTTPDownloader(URLDecoder.decode(m.group(1), "GBK"), URLDecoder.decode(m.group(2), "GBK"), URLDecoder.decode(m.group(3), "GBK"), 10).start();
                    } catch (Exception e) {
                        response = "ERROR -1";
                        e.printStackTrace();
                    }
                } else {
                    response = "ERROR 1";
                }
                httpExchange.sendResponseHeaders(200, response.getBytes().length);
                OutputStream out = httpExchange.getResponseBody();
                out.write(response.getBytes());
                out.close();
                httpExchange.close();
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    }
    
    24.多线程端口扫描
    /*
    import java.io.*;
    import java.net.*;
    */
    int Thread_Num=50;                       //设置默认线程数50
    String host="localhost";
    int minPort;
    int maxPort;
    int portNum;
    
    ScanPort sp[]=new ScanPort[Thread_Num];
    
    minPort=Integer.parseInt(args[1]);
    maxPort=Integer.parseInt(args[2]);
    
    if(args.length == 3 && minPort<maxPort)
    {
        host=args[0];
        minPort=Integer.parseInt(args[1]);
        maxPort=Integer.parseInt(args[2]);
        InetAddress thisComputer;
        byte[] address;
    
        //获取IP地址的字节
        try
        {
            thisComputer=InetAddress.getByName(host);
            address=thisComputer.getAddress();
        }
    
        catch(UnknownHostException e)
        {
            System.out.println("Cannot find host"+host);
        }
    }
    
    if (args.length == 4 && minPort<maxPort)
    {
        host=args[0];
        minPort=Integer.parseInt(args[1]);
        maxPort=Integer.parseInt(args[2]);
        Thread_Num=Integer.parseInt(args[3]);    //自定义线程数
        InetAddress thisComputer;
        byte[] address;
    
        //获取IP地址的字节
        try
        {
            thisComputer=InetAddress.getByName(host);
            address=thisComputer.getAddress();
        }
    
        catch(UnknownHostException e)
        {
            System.out.println("Cannot find host"+host);
        }
    }
    
    //--- 计算待扫瞄端口量 ---//
    portNum=maxPort-minPort+1;
    if(portNum < Thread_Num)
    {
        //--- 如果端口数小于总线程 ---//
        for(int i=0; i<portNum; i++)
        {
            sp[i]=new ScanPort(host,minPort+i,minPort+i,i);
            sp[i].start();
        }
    }
    else
    {
        int startPort = minPort, endPort = minPort;
        int A = portNum / Thread_Num ;
        int B = portNum % Thread_Num;
    
        for(int i=0; i<Thread_Num; i++)
        {
            if(B <= Thread_Num)
            {
                startPort = endPort;
                if ( i!= 0)
                {
                    startPort += 1;
                    endPort = startPort + A -1;
                }
    
                if ( i < B)
                    endPort += 1;
    
                sp[i]=new ScanPort(host,startPort,endPort,i);
                sp[i].start();
            }
            else
            {
                System.out.println("b大于50");
            }
        }
    }
    
    try
    {
    loop:
        while(true)
        {
            for(int i=0; i<Thread_Num; i++)
                if(sp[i].isAlive())
                    continue loop;
            break;
        }
    }
    catch(NullPointerException e)
    {
        System.out.println(e.toString());
    }
    
    class ScanPort extends Thread
    {
        //--- 分别定义目标,开始端口,结束端口,线程标记 ---//
        private String host;
        private int sPort;
        private int ePort;
        private int tag;
        private int i;
    
        //--- 构造函数(重新构造端口) ---//
        ScanPort(String h, int sP, int eP, int t)
        {
            super();
            host=h;
            sPort=sP;
            ePort=eP;
            tag=t;
        }
        public void run()
        {
            //--- 测试端口是否打开 ---//
            for(i=sPort; i<=ePort; i++)
            {
                try
                {
                    Socket s = new Socket(host, i);
                    System.out.println("Host:"+host+" Port: "+i+" is Opening."+tag+"线程");
                    FileOutputStream out1=new FileOutputStream("C:
    eport.txt",true);
                    BufferedOutputStream out2=new BufferedOutputStream(out1);
                    DataOutputStream out=new DataOutputStream(out2);
                    out.writeChars("Host:"+host+" Port:"+i+" is Opening."+tag+" Threads"+"n");
                    out.close();
                    Thread.yield();
                }
    
                catch(IOException e)
                {
                    System.out.println("Host:"+host+" Port: "+i+" is Closed."+tag+"线程");
                }
            }
        }
    }
    
    25.发送带附件的邮件
    /*
    import java.io.*;
    import java.util.*;
    import javax.activation.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    */
    private MimeMessage mimeMsg;
    private Session session;
    private Properties props;
    private boolean needAuth;
    private String username;
    private String password;
    private Multipart mp;
    
    public SendAdditionMail()
    {
        needAuth = true;
        username = "ccue_yuanqichao";
        password = "lianhuanccue";
        setSmtpHost("smtp.sina.com.cn");
        createMimeMessage();
    }
    
    public SendAdditionMail(String smtp)
    {
        needAuth = true;
        username = "ccue_yuanqichao";
        password = "lianhuanccue";
        setSmtpHost(smtp);
        createMimeMessage();
    }
    
    public void setSmtpHost(String hostName)
    {
        System.out.println("设置系统属性:mail.smtp.host = " + hostName);
        if (props == null)
            props = System.getProperties();
        props.put("mail.smtp.host", hostName);
    }
    
    public boolean createMimeMessage()
    {
        try
        {
            System.out.println("准备获取邮件会话对象!");
            session = Session.getDefaultInstance(props, null);
        }
        catch (Exception e)
        {
            System.err.println("获取邮件会话对象时发生错误!" + e);
            return false;
        }
        System.out.println("准备创建MIME邮件对象!");
        try
        {
            mimeMsg = new MimeMessage(session);
            mp = new MimeMultipart();
            return true;
        }
        catch (Exception e)
        {
            System.err.println("创建MIME邮件对象失败!" + e);
        }
        return false;
    }
    
    public void setNeedAuth(boolean need)
    {
        System.out.println("设置smtp身份认证:mail.smtp.auth = " + need);
        if (props == null)
            props = System.getProperties();
        if (need)
            props.put("mail.smtp.auth", "true");
        else
            props.put("mail.smtp.auth", "false");
    }
    
    public void setNamePass(String name, String pass)
    {
        username = name;
        password = pass;
    }
    
    public boolean setSubject(String mailSubject)
    {
        System.out.println("设置邮件主题!");
        try
        {
            mimeMsg.setSubject(mailSubject);
            return true;
        }
        catch (Exception e)
        {
            System.err.println("设置邮件主题发生错误!");
        }
        return false;
    }
    
    public boolean setBody(String mailBody)
    {
        try
        {
            BodyPart bp = new MimeBodyPart();
            bp.setContent("" + mailBody, "text/html;charset=GB2312");
            mp.addBodyPart(bp);
            return true;
        }
        catch (Exception e)
        {
            System.err.println("设置邮件正文时发生错误!" + e);
        }
        return false;
    }
    
    public boolean addFileAffix(String filename)
    {
        System.out.println("增加邮件附件:" + filename);
        try
        {
            BodyPart bp = new MimeBodyPart();
            FileDataSource fileds = new FileDataSource(filename);
            bp.setDataHandler(new DataHandler(fileds));
            bp.setFileName(fileds.getName());
            mp.addBodyPart(bp);
            return true;
        }
        catch (Exception e)
        {
            System.err.println("增加邮件附件:" + filename + "发生错误!" + e);
        }
        return false;
    }
    
    public boolean setFrom(String from)
    {
        System.out.println("设置发信人!");
        try
        {
            mimeMsg.setFrom(new InternetAddress(from));
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    
    public boolean setTo(String to)
    {
        if (to == null)
            return false;
        try
        {
            mimeMsg.setRecipients(javax.mail.Message.RecipientType.TO, InternetAddress.parse(to));
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    
    public boolean setCopyTo(String copyto)
    {
        if (copyto == null)
            return false;
        try
        {
            mimeMsg.setRecipients(javax.mail.Message.RecipientType.CC, InternetAddress.parse(copyto));
            return true;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    
    public boolean sendout()
    {
        try
        {
            mimeMsg.setContent(mp);
            mimeMsg.saveChanges();
            System.out.println("正在发送邮件....");
            Session mailSession = Session.getInstance(props, null);
            Transport transport = mailSession.getTransport("smtp");
            transport.connect((String)props.get("mail.smtp.host"), username, password);
            transport.sendMessage(mimeMsg, mimeMsg.getRecipients(javax.mail.Message.RecipientType.TO));
            System.out.println("发送邮件成功!");
            transport.close();
            return true;
        }
        catch (Exception e)
        {
            System.err.println("邮件发送失败!" + e);
        }
        return false;
    }
    
    String mailbody = " 
    
    java php asp.net编程欢迎您的加入!
    ";
    SendAdditionMail themail = new SendAdditionMail("smtp.sina.com.cn");
    themail.setNeedAuth(true);
    if (!themail.setSubject("TEST"))
    return;
    StringUtil su = new StringUtil();
    if (!themail.setBody(su.getUserEmailText("1", "test", "test")))
    return;
    if (!themail.setTo("test@sina.com"))
    return;
    if (!themail.setFrom("ccue_yuanqichao@sina.com"))
    return;
    if (!themail.addFileAffix("E:\img\183977.jpg"))
    return;
    if (!themail.sendout())
    return;
    else
    return;
    
    26.接收带附件的邮件
    /*
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.mail.*;
    import javax.mail.internet.*;
    */
    /**
    * @author Administrator
    *
    */
    public class PraseMimeMessage{
        private MimeMessage mimeMessage = null;
        private String saveAttachPath ="";//附件下载后的存放目录
    
        private StringBuffer bodytext = new StringBuffer();
        //存放邮件内容的StringBuffer对象
        private String dateformat = "yy-MM-dd HH:mm";//默认的日前显示格式
    
        /**
         * 构造函数,初始化一个MimeMessage对象
          */
        public PraseMimeMessage(){}
        public PraseMimeMessage(MimeMessage mimeMessage){
            this.mimeMessage = mimeMessage;
            System.out.println("create a PraseMimeMessage object........");
        }
    
        public void setMimeMessage(MimeMessage mimeMessage){
            this.mimeMessage=mimeMessage;
        }
    
        /**
        * 
        * 获取发件人的姓名和密码
        * @return 
        */
        public   String getFrom()throws Exception{
            InternetAddress address[] = (InternetAddress[])mimeMessage.getFrom();
            String from = address[0].getAddress();
            if(from == null) from="";
            String personal = address[0].getPersonal();
            if(personal == null) personal="";
            String fromaddr =personal+"<"+from+">";
            return fromaddr;
        }
        /**
         * 获得邮件的收件人,抄送,和密送的地址和姓名,根据所传递的参数的不同
          * "to"----收件人 "cc"---抄送人地址 "bcc"---密送人地址
           */
    
        public String getMailAddress(String type)throws Exception{
            String mailaddr ="";
            String addtype = type.toUpperCase();
            InternetAddress []address = null;
            if(addtype.equals("TO")|| addtype.equals("CC") ||addtype.equals("BCC"))
    
            {if(addtype.equals("TO")){
                address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.TO);
            }else if(addtype.equals("CC")){
                address = (InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.CC);
            }else{
                address=(InternetAddress[])mimeMessage.getRecipients(Message.RecipientType.BCC);
            }
            if(address!=null){
                for(int i=0;i<address.length;i++){
                    String email=address[i].getAddress();
                    if(email==null) email="";
                    else{
                        email=MimeUtility.decodeText(email);
                    }
                    String personal=address[i].getPersonal();
                    if(personal==null) personal="";
                    else{
                        personal=MimeUtility.decodeText(personal);
                    }
                    String compositeto=personal+"<"+email+">";
                    mailaddr+=","+compositeto;
                }
                mailaddr=mailaddr.substring(1);
            }
            }else{
                throw new Exception("Error emailaddr type!");
            }
            return   mailaddr;
        }
    
    
        /**
        * 
        * 获取邮件主题
        */
        public String getSubject()throws MessagingException{
            String subject = "";
            try{
                subject = MimeUtility.decodeText(mimeMessage.getSubject());
                if(subject == null) subject="";
            }catch(Exception exce){
            }
            return subject;
        }
        /*
        * 获取邮件发送日期
        * 
        */
    
        public String getSentDate()throws Exception{
            Date sentdate = mimeMessage.getSentDate();
            SimpleDateFormat format = new SimpleDateFormat(dateformat);
            return format.format(sentdate);
        }
    
        /**
        * 获取邮件正文
        * @return 
        * 
        */
    
        public String getBodyText(){
            return bodytext.toString();
        }
    
        /**
        * 解析邮件,把得到的邮件内容保存到一个StringBuffer对象中,解析邮件
        *   主要是根据MimeType类型的不同执行不同的操作,一步一步的解析
        * 
        * 
        */
    
        public void getMailContent(Part part)throws Exception{
            String contenttype = part.getContentType();
            int nameindex = contenttype.indexOf("name");
            boolean conname =false;
            if(nameindex !=-1) conname=true;
            System.out.println("CONTENTTYPE: "+contenttype);
            if(part.isMimeType("text/plain") && !conname){
                bodytext.append((String)part.getContent());
            }else if(part.isMimeType("text/html") && !conname){
                bodytext.append((String)part.getContent());
            }else if(part.isMimeType("multipart/*")){
                Multipart multipart =(Multipart)part.getContent();
                int counts = multipart.getCount();
                for(int i=0;i<counts;i++){
                    getMailContent(multipart.getBodyPart(i));
                }
            }else if(part.isMimeType("message/rfc822")){
                getMailContent((Part)part.getContent());
            }else{}
        }
    
        /**
        * 
        * 判断此邮件是否需要回执,如果需要回执返回"true",否则返回"false"
        * 
        */
    
    
    
    
        public boolean getReplySign()throws MessagingException{
            boolean replysign = false;
            String needreply[] =   mimeMessage.getHeader("Disposition-Notification-To");
            if(needreply != null){
                replysign=true;
            }
            return replysign;
        }
        /*
        * 获得此邮件的Message-ID
        * 
        */
    
        public String getMessageId()throws MessagingException{
            return mimeMessage.getMessageID();
        }
        /*
        * 【判断此邮件是否已读,如果未读返回返回false,反之返回true】
        * 
        */
    
        public boolean isNew()throws MessagingException{
            boolean isnew = false;
            Flags flags = ((Message)mimeMessage).getFlags();
            Flags.Flag []flag = flags.getSystemFlags();
            System.out.println("flags's length: "+flag.length);
            for(int i=0;i<flag.length;i++){
                if(flag[i] == Flags.Flag.SEEN){
                    isnew=true;
                    System.out.println("seen Message.......");
                    break;}
            }
            return isnew;
        }
    
        /**
        * 
        * 判断此邮件是否包含附件
        * 
        */
    
        public boolean isContainAttach(Part part)throws Exception{
            boolean attachflag = false;
            String contentType = part.getContentType();
            if(part.isMimeType("multipart/*")){
                Multipart mp = (Multipart)part.getContent();
                for(int i=0;i<mp.getCount();i++){
                    BodyPart mpart = mp.getBodyPart(i);
                    String disposition = mpart.getDisposition();
                    if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE))))
                        attachflag = true;
                    else if(mpart.isMimeType("multipart/*")){
                        attachflag = isContainAttach((Part)mpart);
                    }else{
                        String contype = mpart.getContentType();
                        if(contype.toLowerCase().indexOf("application")!= -1) attachflag=true;
                        if(contype.toLowerCase().indexOf("name") != -1) attachflag=true;
                    }
                }
            }else if(part.isMimeType("message/rfc822")){
                attachflag = isContainAttach((Part)part.getContent());
            }
            return attachflag;
        }
    
        /*
        * 保存附件
        * 
        */
        public void saveAttachMent(Part part)throws Exception{
            String fileName="";
            if(part.isMimeType("multipart/*")){
                Multipart mp=(Multipart)part.getContent();
                for(int i=0;i<mp.getCount();i++){
                    BodyPart mpart =mp.getBodyPart(i);
                    String disposition = mpart.getDisposition();
                    if((disposition != null) &&((disposition.equals(Part.ATTACHMENT)) ||(disposition.equals(Part.INLINE)))){
                        fileName = mpart.getFileName();
                        if(fileName.toLowerCase().indexOf("gb2312")!=-1){
                            fileName = MimeUtility.decodeText(fileName);
                        }
                        //saveFile(fileName,mpart.getInputStream());
                        saveFile(fileName,mpart.getInputStream());
    
                    }else if(mpart.isMimeType("multipart/*")){
                        saveAttachMent(mpart);
                    }else{
                        fileName = mpart.getFileName();
                        if((fileName != null) && (fileName.toLowerCase().indexOf("GB2312") !=-1)){
                            fileName=MimeUtility.decodeText(fileName);
                            saveFile(fileName,mpart.getInputStream());
                        }
                    }
                }
            }else if(part.isMimeType("message/rfc822")){
                saveAttachMent((Part)part.getContent());
            }
        }
    
        /**
         * 【设置附件存放路径】
          */
    
        public void setAttachPath(String attachpath){
            this.saveAttachPath = attachpath;
        }
    
        /**
        * 
        * 设置日期显示本格式
        */
        public void setDateFormat(String format)throws Exception{
            this.dateformat = format;
        }
    
        /**
         * 【获得附件存放路径】
          */
    
        public String getAttachPath(){
            return saveAttachPath;
        }
    
        /**
         * 【真正的保存附件到指定目录里】
          */
    
        private void saveFile(String fileName,InputStream in)throws Exception{
    
            String osName = System.getProperty("os.name"); 
            String storedir = getAttachPath();
            String separator = "";
            if(osName == null) osName="";
            if(osName.toLowerCase().indexOf("win") != -1){
                separator="\";
                if(storedir == null || storedir.equals("")) storedir="c:\tmp";
            }else{
                separator ="/";
                storedir = "/tmp";
            }
            File storefile = new File(storedir+separator+fileName);
            System.out.println("storefile's path: "+storefile.toString());
    
    
            BufferedOutputStream bos = null;
            BufferedInputStream bis = null;
            try{
                bos = new BufferedOutputStream(new FileOutputStream(storefile));
                bis = new BufferedInputStream(in);
                int c;
                while((c=bis.read())!= -1){
                    bos.write(c);
                    bos.flush();
                }
            }catch(Exception exception){
                exception.printStackTrace();
                throw new Exception("文件保存失败!");
            }finally{
                bos.close();
                bis.close();
            }
        }
        /**
         * PraseMimeMessage类测试
          */
    
        public static void main(String args[])throws Exception{
            String host = "POP3.163.com";//【POP3.163.com】
            String username ="yuxia2217";//【yuxia2217】
            String password ="*************";//【........】
            Properties props = new Properties();
            Session session = Session.getDefaultInstance(props, null);
            Store store = session.getStore("pop3");
            store.connect(host,username, password);
            Folder folder = store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message message[]=folder.getMessages();
            System.out.println("Messages's length: "+message.length);
            PraseMimeMessage pmm = null;
            for(int i=0;i<message.length;i++){
                pmm = new PraseMimeMessage((MimeMessage)message[i]);
                System.out.println("Message "+i+" subject: "+pmm.getSubject());
                System.out.println("Message "+i+" sentdate: "+pmm.getSentDate());
                System.out.println("Message "+i+" replysign: "+pmm.getReplySign());
                System.out.println("Message "+i+" hasRead: "+pmm.isNew());
                System.out.println("Message "+i+"  containAttachment: "+pmm.isContainAttach((Part)message[i]));
                System.out.println("Message "+i+" form: "+pmm.getFrom());
                System.out.println("Message "+i+" to: "+pmm.getMailAddress("to"));
                System.out.println("Message "+i+" cc: "+pmm.getMailAddress("cc"));
                System.out.println("Message "+i+" bcc: "+pmm.getMailAddress("bcc"));
                pmm.setDateFormat("yy年MM月dd日 HH:mm");
                System.out.println("Message "+i+" sentdate: "+pmm.getSentDate());
                System.out.println("Message "+i+" Message-ID: "+pmm.getMessageId());
                pmm.getMailContent((Part)message[i]);
                System.out.println("Message "+i+" bodycontent: 
    "+pmm.getBodyText());
                pmm.setAttachPath("c:\tmp\coffeecat1124");
                pmm.saveAttachMent((Part)message[i]);
            }
        }
    }
    
    27.Ping
    //import java.net.*;
    
    String host = %%1; //"128.0.0.1"
    boolean %%2;
    try {
        %%2 = InetAddress.getByName(host).isReachable(4000);// 超时应该在4钞以上
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    28.调用Web Service
    /*
    import org.apache.axis.client.*;
    */
    /**
    * 远程调用web service 2008.09.04
    * 需要添加axis.jar,axis-ant.jar,axis-schema.jar,commons-discovery.jar包
    * @author Rascal_hu      http://hi.baidu.com/rascal_hu
    */
    public String getMessage(){
        String msg="";
        try{
            //设置远程地址
            String URL="http://192.168.0.168:3219/WebService/services/Hello";
            Service service=new Service();
            Call call=(Call)service.createCall();
            call.setTargetEndpointAddress(new java.net.URL(URL));
            //设置远程方法
            call.setOperationName("example");
            msg=(String)call.invoke(new Object[]{"Jesun"});//远程方法返回值为String
            //如果远程方法需要接受参数.则上面的写法为:(String)call.invoke(new Object[]{参数1,参数2,..});
            //如果远程方法不需要接受参数,则写为:(String)call.invoke(new Object[]{});
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("远程调用webservice失败!");
        }
        return msg;
    }
    CallWebService callWeb=new CallWebService();
    String msg=callWeb.getMessage();
    System.out.println(msg);
    
    29.HTTP代理服务器
    /*
    import java.net.*;
    import java.io.*;
    */
    HttpClient httpClient = new HttpClient();   
    // 设置代理服务器的ip地址和端口   
    //      httpClient.getHostConfiguration().setProxy("127.0.0.1", 8888);   
    //      // 使用抢先认证   
    //      httpClient.getParams().setAuthenticationPreemptive(true);   
    GetMethod method = new GetMethod("http://www.javaeye.com/topic/154258");   
    HostConfiguration config = httpClient.getHostConfiguration();   
    config.setProxy("127.0.0.1", 8888);   
    //      method.addRequestHeader("Content-type", "text/xml; charset=utf-8");   
    try {   
        int statusCode = httpClient.executeMethod(method);   
        if (statusCode != HttpStatus.SC_OK) {   
            System.err.println("Method failed: " + method.getStatusLine());   
        }   
        String resultXml = method.getResponseBodyAsString();   
        System.out.println(resultXml);   
    } catch (HttpException e) {   
        e.printStackTrace();   
    } catch (IOException e) {   
        e.printStackTrace();   
    }
    
    30.创建启动线程
    public void myFunc()
    {
        %%1
    }
    Thread myThread=new Thread(new ThreadStart(myFunc));
    myThread.Start();
    
    31.线程挂起唤醒
    myThread.Sleep(Infinite);
    myThread.Suspend();
    
    32.线程插入终止
    myThread.Abort();
    myThread.Join();
    
    33.HTTP多线程下载
    /*
    import java.io.*;
    import java.net.*;
    */
    /**
    * HTTP的多线程下载工具。
    * 
    * @author 赵学庆 www.java2000.net
    */1.public class HTTPDownloader extends Thread {
        // 要下载的页面1.  private String page;
        // 保存的路径1.  private String savePath;
        // 线程数1.  private int threadNumber = 2;
        // 来源地址1.  private String referer;
        // 最小的块尺寸。如果文件尺寸除以线程数小于这个,则会减少线程数。1.  private int MIN_BLOCK = 10 * 1024;
        public static void main(String[] args) throws Exception {
            HTTPDownloader d = new HTTPDownloader("http://www.xxxx.net/xxxx.rar", "d://xxxx.rar", 10);
            d.down();
        }
        public void run() {
            try {
                down();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        /**
        * 下载操作
        * 
        * @throws Exception
        */1.  public void down() throws Exception {
            URL url = new URL(page); // 创建URL1.    URLConnection con = url.openConnection(); // 建立连接1.    int contentLen = con.getContentLength(); // 获得资源长度1.    if (contentLen / MIN_BLOCK + 1 < threadNumber) {
            threadNumber = contentLen / MIN_BLOCK + 1; // 调整下载线程数1.    }
            if (threadNumber > 10) {
                threadNumber = 10;
            }
            int begin = 0;
            int step = contentLen / threadNumber;
            int end = 0;
            for (int i = 0; i < threadNumber; i++) {
                end += step;
                if (end > contentLen) {
                    end = contentLen;
                }
                new HTTPDownloaderThread(this, i, begin, end).start();
                begin = end;
            }
        }
        public HTTPDownloader() {
        }
        /**
        * 下载
        * 
        * @param page 被下载的页面
        * @param savePath 保存的路径
        */1.  public HTTPDownloader(String page, String savePath) {
            this(page, savePath, 10);
        }
        /**
        * 下载
        * 
        * @param page 被下载的页面
        * @param savePath 保存的路径
        * @param threadNumber 线程数
        */  public HTTPDownloader(String page, String savePath, int threadNumber) {
            this(page, page, savePath, 10);
        }
        /**
        * 下载
        * 
        * @param page 被下载的页面
        * @param savePath 保存的路径
        * @param threadNumber 线程数
        * @param referer 来源
        */  public HTTPDownloader(String page, String referer, String savePath, int threadNumber) {
            this.page = page;
            this.savePath = savePath;
            this.threadNumber = threadNumber;
            this.referer = referer;
        }
        public String getPage() {
            return page;
        }
        public void setPage(String page) {
            this.page = page;
        }
        public String getSavePath() {
            return savePath;
        }
        public void setSavePath(String savePath) {
            this.savePath = savePath;
        }
        public int getThreadNumber() {
            return threadNumber;
        }
        public void setThreadNumber(int threadNumber) {
            this.threadNumber = threadNumber;
        }
        public String getReferer() {
            return referer;
        }
        public void setReferer(String referer) {
            this.referer = referer;
        }
    }
    /**
    * 下载线程
    * 
    */1.class HTTPDownloaderThread extends Thread {
        HTTPDownloader manager;
        int startPos;
        int endPos;
        int id;
        int curPos;
        int BUFFER_SIZE = 4096;
        int readByte = 0;
        HTTPDownloaderThread(HTTPDownloader manager, int id, int startPos, int endPos) {
            this.id = id;
            this.manager = manager;
            this.startPos = startPos;
            this.endPos = endPos;
        }
        public void run() {
            // System.out.println("线程" + id + "启动");1.    // 创建一个buff1.    BufferedInputStream bis = null;
            RandomAccessFile fos = null;
            // 缓冲区大小1.    byte[] buf = new byte[BUFFER_SIZE];
            URLConnection con = null;
            try {
                File file = new File(manager.getSavePath());
                // 创建RandomAccessFile1.      fos = new RandomAccessFile(file, "rw");
                // 从startPos开始1.      fos.seek(startPos);
                // 创建连接,这里会为每个线程都创建一个连接1.      URL url = new URL(manager.getPage());
                con = url.openConnection();
                con.setAllowUserInteraction(true);
                curPos = startPos;
                // 设置获取资源数据的范围,从startPos到endPos1.      con.setRequestProperty("Range", "bytes=" + startPos + "-" + endPos);
                // 盗链解决1.      con.setRequestProperty("referer", manager.getReferer() == null ? manager.getPage() : manager.getReferer());
                con.setRequestProperty("userAgent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
                // 下面一段向根据文件写入数据,curPos为当前写入的未知,这里会判断是否小于endPos,1.      // 如果超过endPos就代表该线程已经执行完毕1.      bis = new BufferedInputStream(con.getInputStream());
                while (curPos < endPos) {
                    int len = bis.read(buf, 0, BUFFER_SIZE);
                    if (len == -1) {
                        break;
                    }
                    fos.write(buf, 0, len);
                    curPos = curPos + len;
                    if (curPos > endPos) {
                        .          // 获取正确读取的字节数1.          readByte += len - (curPos - endPos) + 1;
                    } else {
                        readByte += len;
                    }
                }
                // System.out.println("线程" + id + "已经下载完毕:" + readByte);1.      bis.close();
                fos.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
    
    34.MP3播放
    //必须下载 jmf包
    //import javax.media.bean.playerbean.MediaPlayer; //必须下载 jmf 媒体播放包 
    MediaPlayer player;
    player = new MediaPlayer(); 
    setLayout(new FlowLayout()); 
    try{ 
        player.setMediaLocation("file:/F:\音乐\mp3\黑白配.mp3");// <<file:/>>不能删除 音频文件路径 
    } catch (Exception e) { 
        System.out.println("文件不存在"); 
    }
    player.start();
    player.stop();
    
    35.WAV播放
    /*
    import javax.sound.sampled.*;
    import java.io.*;
    */
    private AudioFormat format;
    private byte[] samples;
    private String filename;
    try {
        // open the audio input stream
        AudioInputStream stream =AudioSystem.getAudioInputStream(new File(filename));
        format = stream.getFormat();
        // get the audio samples
        samples = getSamples(stream);
    }
    catch (UnsupportedAudioFileException ex) {
        ex.printStackTrace();
    }
    catch (IOException ex) {
        ex.printStackTrace();
    }
    
    private byte[] getSamples(AudioInputStream audioStream) {
        // get the number of bytes to read
        int length = (int)(audioStream.getFrameLength() * format.getFrameSize());
    
        // read the entire stream
        byte[] samples = new byte[length];
        DataInputStream is = new DataInputStream(audioStream);
        try {
            is.readFully(samples);
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    
        // return the samples
        return samples;
    }
    
    public void play(InputStream source) {
    
        // use a short, 100ms (1/10th sec) buffer for real-time
        // change to the sound stream
        int bufferSize = format.getFrameSize() *
            Math.round(format.getSampleRate() / 10);
        byte[] buffer = new byte[bufferSize];
    
        // create a line to play to
        SourceDataLine line;
        try {
            DataLine.Info info =
                new DataLine.Info(SourceDataLine.class, format);
            line = (SourceDataLine)AudioSystem.getLine(info);
            line.open(format, bufferSize);
        }
        catch (LineUnavailableException ex) {
            ex.printStackTrace();
            return;
        }
    
        // start the line
        line.start();
    
        // copy data to the line
        try {
            int numBytesRead = 0;
            while (numBytesRead != -1) {
                numBytesRead =
                    source.read(buffer, 0, buffer.length);
                if (numBytesRead != -1) {
                    line.write(buffer, 0, numBytesRead);
                }
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    
        // wait until all data is played, then close the line
        line.drain();
        line.close();
    }
    
    throws Exception
        String filename=%%1;
        InputStream stream =new ByteArrayInputStream(sound.getSamples());
        // play the sound
        sound.play(stream);
  • 相关阅读:
    错误 1324。文件夹路径 .. 中含有无效的字符
    linux下 tar解压 gz解压 bz2等各种解压文件使用方法
    取消EXCEL 2007/2010中邮箱地址的自动链接
    Windows2000/XP启动过程详解
    Ubuntu下安装apache2,mysql,php,wordpress.
    offcie2007,2010,2012中快速删除指定的页面.
    mysql连接,修改密码,增加用户,显示,导入导出
    键盘各按键的使用
    cvim 使用
    matlab基础知识(basic operation)
  • 原文地址:https://www.cnblogs.com/struCoder/p/3370031.html
Copyright © 2020-2023  润新知