62,567
社区成员




import java.io.*;
import java.util.*;
import javax.comm.*;
/**
* 读串口的例程
* @author zcj
*/
public class Test {
static CommPortIdentifier portId;
static Enumeration portList;// 枚举类
InputStream inputStream;
SerialPort serialPort;
public static void main(String[] args) {
//枚举出系统所有的RS232端口
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL)
{
if (portId.getName().equals("COM1"))/* 找Windows下的第一个串口*/ {
//if (portId.getName().equals("/dev/term/a"))/* 找Unix-like系统下的第一个串口 */{
new Test().print();
}
}
}
}
public void print() {
try {
//获得串口对象
serialPort = (SerialPort) portId.open("TestApp", 2000);
// 获取端口的输入流对象
inputStream = serialPort.getInputStream();
//读取输入流
int ch;
StringBuffer sb = new StringBuffer();
while((ch=inputStream.read())>0){
sb.append((char)ch);
}
System.out.println("读取到的内容为:"+sb.toString());
}catch (Exception e) {
e.printStackTrace();
}
serialPort.close();
}
}