java串口 来电显示
一.使用sun公司的comm.jar1.配置(下载comm.jar包http://code.google.com/p/smslib/downloads/detail?name=javacomm20-win32.zip&can=2&q=)
(1).将包下的javax.comm.properties放到jdk home/jre/lib下
(2).将包下的win32com.dll放到jdk home/jre/bin下(也可以放到windows下的system32下)
(3).将comm.jar放到jdk home/jre/lib/ext下
2.java代码
package comm;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Enumeration;import java.util.TooManyListenersException;import javax.comm.CommDriver;import javax.comm.CommPortIdentifier;import javax.comm.PortInUseException;import javax.comm.SerialPort;import javax.comm.SerialPortEvent;import javax.comm.SerialPortEventListener;import javax.comm.UnsupportedCommOperationException;public class SimpleWrite {public static void main(String[] args) {// System.loadLibrary("win32com");CommDriver driver = null;String driverName = "com.sun.comm.Win32Driver";// SerialPort sPort = (SerialPort) driver.getCommPort("COM4",// CommPortIdentifier.PORT_SERIAL);Enumeration<CommPortIdentifier> enumeration = CommPortIdentifier.getPortIdentifiers();while (enumeration.hasMoreElements()) {CommPortIdentifier portId = enumeration.nextElement();System.out.println(portId.getName() + "============");if (portId.getName().equals("COM1")) {try {System.out.println("jjj");final SerialPort sp = (SerialPort) portId.open("SimpleWrite", 1000);sp.setSerialPortParams(2400, SerialPort.DATABITS_8,SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);final InputStream is = sp.getInputStream();final OutputStream os = sp.getOutputStream();os.write(100);os.flush();os.close();//Set notifyOnDataAvailable to true to allow event driven input. sp.notifyOnDataAvailable(true);// Set notifyOnBreakInterrup to allow event driven break// handling.sp.notifyOnBreakInterrupt(true);// Set receive timeout to allow breaking out of polling loop// during input handling.sp.enableReceiveTimeout(30);final StringBuffer linkWgt = new StringBuffer();// 存放获取的数据sp.addEventListener(new SerialPortEventListener() {@Overridepublic void serialEvent(SerialPortEvent e) {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) {} else {linkWgt.append((char) newData);}} catch (IOException ex) {System.err.println(ex);return;}}// Append received data to messageAreaIn.try {System.out.println("linkWgt ---------
页:
[1]