谁有java通讯串口的例子请发个我,谁的例子能用直接给分直接结贴!
目前手头试了2个程序都有问题,所以希望看下成功的例子!
1,打开串口
2,初始化串口
3,读写串口
4,关闭串口
用到的是javax.comm包,或有其他的也可!

解决方案 »

  1.   

    这是我毕业设计中的一段代码,向串口中写数据
    import java.io.*;
    import java.util.*;
    import javax.comm.*;
    /**
     *
     * @author Administrator
     */
    public class CommWrite extends Thread{
        private static Enumeration portList;
        private static CommPortIdentifier portId;
        private static SerialPort serialPort;
        private String messageString;    
        private OutputStream outputStream;
        private String comName;
        public static void main(String[] args){
            new CommWrite("COM2","你好");
        }
        public CommWrite(String comName,String message){
            this.comName = comName;
            messageString = message;
            this.start();
        }
        public void run(){
            write(messageString);
        }
        private void write(String str) {
            portList = CommPortIdentifier.getPortIdentifiers();        while (portList.hasMoreElements()) {
                portId = (CommPortIdentifier) portList.nextElement();
                if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                    if (portId.getName().equals(this.comName)) {
                        try {
                            serialPort = (SerialPort)
                                portId.open("SimpleWriteApp", 2000);
                        } catch (PortInUseException e) {}
                        try {
                            outputStream = serialPort.getOutputStream();
                        } catch (IOException e) {}
                        try {
                            serialPort.setSerialPortParams(9600,
                                SerialPort.DATABITS_8,
                                SerialPort.STOPBITS_1,
                                SerialPort.PARITY_NONE);
                        } catch (UnsupportedCommOperationException e) {}
                        try {
                            outputStream.write(str.getBytes());
                            serialPort.close();
                        } catch (IOException e) {}
                    }
                }
            }
        }
    }
      

  2.   

    while(portList.hasMoreElements())这一条前面我加了
    System.out.print(portList.hasMoreElements());
    打出来居然是false,可是我电脑上明明有2个串口都是好的。
    奇怪!
      

  3.   

    bayougeng    OK 3Q了 ,数据出来了!结贴!
      

  4.   

    哇,真的那么灵?哈哈!
    说实话,在google上和baidu上,我真没看到很好的关于串口通讯的例子。
    大多数都是按照官方文档翻译过来的。很容易出问题。
    我blog里的方法,确实还是蛮实用的。