使用此代码之前的环境配置:
首先用的是 javacomm20-win32.zip 这个压缩包 (javax.comm,自己可以到网上下载)
前提条件是:将这种配置放在外部的JDK环境之下(供参考)
①.解压完之后将win32com.dll 放到 C:\Program Files\Java\jdk1.7.0_03\bin下
②.将comm.jar 价包拷贝到 C:\Program Files\Java\jre7\lib\ext
③.javax.comm.properties 拷贝到 C:\Program Files\Java\jre7\lib
用rxtxComm来配置环境的话步骤如下:
step1.在eclipse中新建一个工程(根据你自己的需要,Applet,tomcat,java工程等均可)。
step2.在工程下建一个lib文件夹。
step3.将rxtx-2.1-7-bins-r2.zip解压缩,得到文件夹[rxtx-2.1-7-bins-r2]。
step4.将[rxtx-2.1-7-bins-r2]/RXTXcomm.jar这个文件copy到step2创建的lib中。
step5.将[rxtx-2.1-7-bins-r2]/Windows/i368-mingw32目录下的两个dll文件copy到step2创建的lib中。
step6.在工程上右键 ->Properties -> Java Builder Path -> Libraries -> Add JARs -> 选择step2中创建的lib目录下的RXTXcomm.jar -> OK。
step7.最关键的一步。点RXTXcomm.jar前面的小加号(+) -> 选择Native library location -> 点右边一列按钮中的Edit… -> 选择step2中创建的lib目录 -> OK
//核心代码
public class SerialConnection implements SerialPortEventListener {
private SerialDemo parent;
private TextArea messageAreaOut;
private TextArea messageAreaIn;
private SerialParameters parameters;
private OutputStream os;
private InputStream is;
private CommPortIdentifier portId;
private SerialPort sPort;
private boolean open;
/**
* Creates a SerialConnection object andinitilizes variables passed in as
* params.
*
* @param parent
* A SerialDemo object.
* @param parameters
* A SerialParameters object.
* @param messageAreaOut
* The TextArea that messages that are to besent out of the
* serial port are entered into.
* @param messageAreaIn
* The TextArea that messages comming into the serial port are
* displayed on.
*/
public SerialConnection(SerialDemo parent, SerialParameters parameters,
TextArea messageAreaOut, TextArea messageAreaIn) {
this.parent= parent;
this.parameters= parameters;
this.messageAreaOut= messageAreaOut;
this.messageAreaIn= messageAreaIn;
open= false;
}
public void openPort() throws SerialConnectionException {
//Obtain a CommPortIdentifier object for the port you want to open.
}
/**
* Attempts to open a serial connection andstreams using the parameters in
* the SerialParameters object. If it isunsuccesfull at any step it returns
* the port to a closed state, throws a
*<code>SerialConnectionException</code>, and returns.
*
* Gives a timeout of 30 seconds on theportOpen to allow other applications
* to reliquish the port if have it open and nolonger need it.
*/
public void openConnection() throws SerialConnectionException {
try{
portId= CommPortIdentifier.getPortIdentifier(parameters
.getPortName());
System.out.println("串口号是:" + portId.getName());
}catch (NoSuchPortException e) {
throw new SerialConnectionException(e.getMessage());
}
//Open the port represented by the CommPortIdentifier object. Give
//the open call a relatively long timeout of 30 seconds to allow
//a different application to relinquish the port if the user
//wants to.
//打开需要的延迟,并获取commPort对象
//可以再打开sPort后多次得到发送与解析的数据
if(portId.isCurrentlyOwned()) {
sPort.close();
}
try{
sPort= (SerialPort) portId.open("SerialDemo", 30000);
System.out.println("sPort串口已打开");
}catch (PortInUseException e) {
throw new SerialConnectionException(e.getMessage());
}
//Set the parameters of the connection. If they won't set, close the
//port before throwing an exception.
//再次设置连接时的参数
try{
setConnectionParameters();
}catch (SerialConnectionException e) {
sPort.close();
}
try{
//发送的
os= sPort.getOutputStream();// OutputStream object that can be used
//to write to the port
//System.out.println("输入流是:"+os);
System.out.println(os+"哪里");
}catch (IOException e) {
sPort.close();
throw new SerialConnectionException("Error opening i/o streams");
}
System.out.println("发送的指令在这里获取了" +messageAreaOut.getText());
String osstr = messageAreaOut.getText();
byte[]b = hexStringToBytes(osstr);
System.out.println("16进制的字符串已经导入到byte[],其中b[0]:" + b[0]);
try{
os.write(b);
System.out.println("os开始发送指令了");
}catch (IOException e) {
System.err.println("OutputStreamwrite error: " + e);
}
try{
//接收的
is= sPort.getInputStream();
// InputStream object that can be used to read from the port
System.out.println(is+"这里");
}catch (IOException e) {
sPort.close();
throw new SerialConnectionException("Error opening i/o streams");
}
System.out.println("发送的指令在这里获取了" +messageAreaIn.getText());
//Add this object as an event listener for the serial port.
try{
sPort.addEventListener(this);
System.out.println("对象sPort进行监听");
}catch (TooManyListenersException e) {
sPort.close();
throw new SerialConnectionException("too many listeners added");
}
//Set notifyOnDataAvailable to true to allow event driven input.
//主要是这一部分起监听执行接收返回数据的作用
if(b[0] ==18){
sPort.notifyOnDataAvailable(true);
}else{
messageAreaIn.append("\n---Dataanalytical failure!---\n");
}
//Set notifyOnBreakInterrup to allow event driven break handling.设置中断事件
sPort.notifyOnBreakInterrupt(true);
//Set receive timeout to allow breaking out of polling loop during
//input handling.
try{
sPort.enableReceiveTimeout(30);
}catch (UnsupportedCommOperationException e) {
}
//Add ownership listener to allow ownership event handling.
//portId.addPortOwnershipListener(this);
open= true;
}
//这是将16进形式的字符串要转化为byte[],就是要以两位的形式读取
public static final byte[] hexStringToBytes(String s) {
byte[]bytes;
bytes= new byte[s.length() / 2];
for(int i = 0; i < bytes.length; i++) {
bytes[i]= (byte) Integer.parseInt(s.substring(2 * i, 2 * i + 2),
16);
}
return bytes;
}
/**
* Sets the connection parameters to thesetting in the parameters object.
* If set fails return the parameters object toorigional settings and throw
* exception.
*/
public void setConnectionParameters() throws SerialConnectionException {
System.out.println("开始设置参数");
//Save state of parameters before trying a set.
int oldBaudRate = sPort.getBaudRate();
int oldDatabits = sPort.getDataBits();
int oldStopbits = sPort.getStopBits();
int oldParity = sPort.getParity();
int oldFlowControl = sPort.getFlowControlMode();
//Set connection parameters, if set fails return parameters object
//to original state.
try{
sPort.setSerialPortParams(parameters.getBaudRate(),
parameters.getDatabits(),parameters.getStopbits(),
parameters.getParity());
}catch (UnsupportedCommOperationException e) {
parameters.setBaudRate(oldBaudRate);
parameters.setDatabits(oldDatabits);
parameters.setStopbits(oldStopbits);
parameters.setParity(oldParity);
throw new SerialConnectionException("Unsupported parameter");
}
//Set flow control.
try{
sPort.setFlowControlMode(parameters.getFlowControlIn()
|parameters.getFlowControlOut());
}catch (UnsupportedCommOperationException e) {
throw new SerialConnectionException("Unsupported flow control");
}
}
/**
* Close the port and clean up associatedelements.
*/
public void closeConnection() {
//If port is alread closed just return.
if(!open) {
return;
}
//Check to make sure sPort has reference to avoid a NPE.
if(sPort != null) {
try{
//close the i/o streams.
os.close();
is.close();
}catch (IOException e) {
System.err.println(e);
}
//Close the port.
sPort.close();
//Remove the ownership listener.
//portId.removePortOwnershipListener(this);
}
open= false;
}
/**
* Send a one second break signal.
*/
public void sendBreak() {
System.out.println("写入中断");
sPort.sendBreak(1000);
messageAreaIn.append("\n---BREAK RECEIVED ---\n");
}
/**
* Reports the open status of the port.
*
* @return true if port is open, false if portis closed.
*/
public boolean isOpen() {
return open;
}
/**
* Handles SerialPortEvents. The two types ofSerialPortEvents that this
* program is registered to listen for areDATA_AVAILABLE and BI. During
* DATA_AVAILABLE the port buffer is read untilit is drained, when no more
* data is availble and 30ms has passed themethod returns. When a BI event
* occurs the words BREAK RECEIVED are writtento the messageAreaIn.
*/
/**
* Handles ownership events. If aPORT_OWNERSHIP_REQUESTED event is received
* a dialog box is created asking the user ifthey are willing to give up
* the port. No action is taken on other typesof ownership events.
*/
public void ownershipChange(int type) {
if(type == CommPortOwnershipListener.PORT_OWNERSHIP_REQUESTED) {
PortRequestedDialog prd = new PortRequestedDialog(parent);
}
}
/**
* A class to handle<code>KeyEvent</code>s generated by the messageAreaOut.
* When a <code>KeyEvent</code>occurs the <code>char</code> that is
* generated by the event is read, converted toan <code>int</code> and
* writen to the<code>OutputStream</code> for the port.
*/
public void serialEvent(SerialPortEvent e) {
String driver="oracle.jdbc.OracleDriver";
Statement statement;
String url="jdbc:oracle:thin:@localhost:1521:xe";
String user="wcs";
String pwd="123456";
//TODO Auto-generated method stub
//Create a StringBuffer and int to receive input data.
StringBuffer inputBuffer = new StringBuffer();
System.out.println("进入到了SerialEvent 来读取返回的数据");
int newData = 0;
//Determine type of event.
switch(e.getEventType()) {
//Read data until -1 is returned. If \r is received substitute
//\n for correct newline handling.
case SerialPortEvent.DATA_AVAILABLE:
while(newData != -1) {
try{
newData= is.read();
if(newData == -1) {
break;
}
if('\r' == (char) newData) {
inputBuffer.append('\n');
}else {
inputBuffer.append(Integer
.toHexString(
((newData& 0x000000FF) | 0xFFFFFF00))
.substring(6).toUpperCase()
+" ");
}
}catch (IOException ex) {
System.err.println(ex);
return;
}
}
//Append received data to messageAreaIn.
messageAreaIn.append("Dataanalytical results:"+ new String(inputBuffer) + "\n");
System.out.println("看到了返回的数据"+messageAreaIn.getText());
String osstr = messageAreaIn.getText();
String s=osstr.substring(23, 26);
double db=Integer.parseInt(s.trim(),16);
System.out.println(db);
//数据开始存入数据库中
try {
Class.forName(driver);
Connection conn = DriverManager.getConnection(url, user, pwd);
if (!conn.isClosed()) {
System.out.println("Succeeded connecting to the Database!");
statement = conn.createStatement();
//一条数据
String sql = "insert into student(id,name,password,idcard_no,telephone,classname,buildings_id,dormitory_id,university_status ) values("+ db+",'张龙',123,410381194302256528,13666701234,'通信01',1,101,0)";
ResultSet rs = statement.executeQuery(sql);
String name;
while (rs.next()) {
name = rs.getString("link_name");
System.out.println(name);
}
}
} catch (Exception e1) {
e1.printStackTrace();
}
break;
//If break event append BREAK RECEIVED message.
case SerialPortEvent.BI:
messageAreaIn.append("\n---BREAK RECEIVED ---\n");
}
}
}
详尽代码会打包供下载。