[心缘地方]同学录
首页 | 功能说明 | 站长通知 | 最近更新 | 编码查看转换 | 代码下载 | 常见问题及讨论 | 《深入解析ASP核心技术》 | 王小鸭自动发工资条VBA版
登录系统:用户名: 密码: 如果要讨论问题,请先注册。

[整理]javax.comm串口操作的小实用类~~

上一篇:[备忘]Java线程的sleep方法被中断时,应该处理异常~~
下一篇:[转帖]怎样限制PPS占用带宽~~~[证明有效]

添加日期:2011/11/16 17:26:51 快速返回   返回列表 阅读5023次
网址:http://java.sun.com/products/javacomm/

首先,要做三步:
win32com.dll放到jre的/bin目录下。
javax.comm.properties放到jre的lib目录下。
comm.jar放到随便哪个classPath里就行了,能引用到即可。

操作类代码如下,供参考:


import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

import javax.comm.CommPortIdentifier;
import javax.comm.NoSuchPortException;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;

public class ComPortUtil {

    static SerialPort serialPort = null;
    static CommPortIdentifier portId = null;

    /**
     * 打开串口.
     * 
     * @param port
     *            串口名
     * @return 成功失败
     */
    public static boolean OpenPort(String port) {
        CommPortIdentifier portId = null;
        try {
            // 打开串口,如com1,com2什么的
            portId = CommPortIdentifier.getPortIdentifier(port);
        } catch (NoSuchPortException e) {
            return false;
        }

        try {
            // 使用串口的程序名称,超时时间
            serialPort = (SerialPort) portId.open("Hello World程序名称", 100);
        } catch (PortInUseException e1) {
            return false;
        }
        if (serialPort == null) {
            return false;
        }

        try {
            // 设置波特率什么的
            serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8,
                    SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

            // 接收超时时间100毫秒
            serialPort.enableReceiveTimeout(100);
        } catch (UnsupportedCommOperationException e) {
            return false;
        }
        return true;
    }

    /**
     * 读数据.
     * 
     * @return 读取的数据.
     */
    public static byte[] Read() {
        if (serialPort == null) {
            return null;
        }

        byte[] data = new byte[254];
        try {
            InputStream in = serialPort.getInputStream();
            int length = in.read(data);
            // length是读取的真实长度,可以根据它截取一下数组。
            byte[] trueData = new byte[length];
            System.arraycopy(data, 0, trueData, 0, length);
            return trueData;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 写数据.
     * 
     * @param data
     *            数据
     * @return 成功失败
     */
    public static boolean Write(byte[] data) {
        if (serialPort != null) {
            try {
                if (serialPort.getOutputStream() == null) {
                    return false;
                }
                serialPort.getOutputStream().write(data);
                return true;
            } catch (IOException e) {
                return false;
            }
        }
        return false;
    }

    /**
     * 关闭串口
     * 
     * @return 成功失败
     */
    public static boolean ClosePort() {
        if (serialPort != null) {
            serialPort.notifyOnDataAvailable(false);

            try {
                if (serialPort.getInputStream() == null) {
                    return false;
                }
                serialPort.getInputStream().close();

                if (serialPort.getOutputStream() == null) {
                    return false;
                }
                serialPort.getOutputStream().close();
                serialPort.removeEventListener();
                serialPort.close();
                return true;
            } catch (IOException e) {
                e.printStackTrace();
                return false;
            } finally {
                portId = null;
                serialPort = null;
            }
        }
        return false;
    }

    /**
     * 取得串口列表
     * 
     * @return 串口列表
     */
    @SuppressWarnings("unchecked")
    public static List<String> getComList() {
        List<String> comList = new ArrayList<String>();

        // 返回枚举,包括串口和并口。
        Enumeration portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            CommPortIdentifier port = (CommPortIdentifier) portList
                    .nextElement();
            // 如果类型是串口,则添加。
            if (port.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                comList.add(port.getName().toUpperCase());
            }
        }
        return comList;
    }

    public static void main(String[] args) {

        ComPortUtil.OpenPort("COM1");
        ComPortUtil.Write(new byte[] { (byte) 0xFF, (byte) 0xFF, (byte) 0x86,
                (byte) 0xFA, 0x7C, (byte) 0xFF });
        byte[] data = ComPortUtil.Read();
        for (byte b : data) {
            System.out.println(b);
        }
        ComPortUtil.ClosePort();
    }
}

 

评论 COMMENTS
没有评论 No Comments.

添加评论 Add new comment.
昵称 Name:
评论内容 Comment:
验证码(不区分大小写)
Validation Code:
(not case sensitive)
看不清?点这里换一张!(Change it here!)
 
评论由管理员查看后才能显示。the comment will be showed after it is checked by admin.
CopyRight © 心缘地方 2005-2999. All Rights Reserved