串口開發 comm.jar

-------------------------- 下載資源

 1、下載java Communications api開發包。

 

如:http://download.csdn.net/detail/zzfantasysy/4008004

---------------------------開始配置


 2、將win32com.dll拷貝入C:\j2sdk1.4.2_04\bin

 3、將comm.jar拷貝入C:\j2sdk1.4.2_04\jre\lib\ext

 4、將javax.comm.properties拷貝入C:\j2sdk1.4.2_04\jre\lib

 

--------------------------開始測試

 5、編譯CommTest.java文件

 import java.io.*;

 import java.util.*;

 import javax.comm.*;

 public class CommTest{

 public static void main(String[] args){

 SerialPort serialPort=null;

 DataOutputStream doutput=null;

 InputStream inputStream;

 CommPortIdentifier portId=null;

 String messageString="hello \n";

 try{

 portId=CommPortIdentifier.getPortIdentifier("COM1");

 }catch(NoSuchPortException ne) {

 System.out.println("ne"); ne.printStackTrace();

 }

 try{

 serialPort=(SerialPort) portId.open("TestComm", 5);

 OutputStream output = serialPort.getOutputStream();

 doutput=new DataOutputStream(output);

 inputStream = serialPort.getInputStream();

 }catch(PortInUseException ex) {

 System.out.println("ex"); ex.printStackTrace();

 }catch(IOException ie) {

 System.out.println("ie");

 ie.printStackTrace();

 //serialPort.close();

 }

 try {

 serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

 } catch (UnsupportedCommOperationException e) {}

 }

 try {

 doutput.write(messageString.getBytes());

 } catch (IOException e) {}

 }

 6、串口打開後,用InputStream和DataOutputStream讀寫就可以了。

 7、由於串口爲共享資源,所以在設計程序時應採用單例模式。

發佈了13 篇原創文章 · 獲贊 2 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章