日期:2014-05-20 浏览次数:21077 次
CommPortIdentifier portId;
Enumeration en = CommPortIdentifier.getPortIdentifiers();
// iterate through the ports.
while(en.hasMoreElements()) {
portId = (CommPortIdentifier) en.nextElement();
System.out.println(portId.getName());
if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
System.out.println(portId.getName());
}
}
portId = CommPortIdentifier.getPortIdentifier("COM1");
SerialPort sPort = (SerialPort) portId.open("串口所有者名称", 1000);
System.out.println("start-----------");
final InputStream is = sPort.getInputStream();
sPort.addEventListener(new SerialPortEventListener() {
public void serialEvent(SerialPortEvent e) {
//System.out.println("-->" + e.getEventType());
if(e.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
try {
//System.out.println(is.available());
int x = 0;
byte[] msgPack = new byte[35];
while(true) {
int j = is.read(msgPack, x, msgPack.length - x);
System.out.println("j=" + j);
if(j <= 0)
break;
x += j;
if(false)
break;
// System.out.println("x->" + x);
// for(int i = 0;i < 4;i++) {
// int newData;
// if((newData = is.read()) != -1) {
// msgPack[i] = (byte) newData;
// System.out.println(newData);
// } else {
// break;
// }
// System.out.println("--------");
// }
}
System.out.println("x-> " + x);
for(byte a : msgPack) {
System.out.print(Integer.toHexString(a) + " ");
}
System.out.println();
System.out.println(new String(msgPack, 0, 34));
if(1 == 1)
return;
} catch(Exception es) {
es.printStackTrace();
}
}
}
});
sPort.notifyOnDataAvailable(true);
sPort.setSerialPortParams(9600, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
------解决方案--------------------
http://download.oracle.com/docs/cd/E17802_01/products/products/javacomm/reference/api/index.html
在线官方文档