我有一个简单的类,使用RXTXcomm.jar类读取和写入数据到COM1。在我打开连接并写一个新行后,没有什么可读的。 inputStream的available()始终返回0.
public class ComPortUtility() {
CommPort commPort;
SerialPort serialPort;
InputStream in;
OuputStream out;
int timeout = 10000;
public boolean connect()
{
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier("COM1");
if ( portIdentifier.isCurrentlyOwned() )
{
System.out.println("Error: Port is currently in use");
return false;
}
else
{
this.commPort = portIdentifier.open(this.getClass().getName(),this.timeout);
if ( commPort instanceof SerialPort )
{
this.serialPort = (SerialPort) commPort;
//setting baud rate, data bits, stop bit, parity
serialPort.setSerialPortParams(19200,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
//setting flow control
serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
System.out.println("BaudRate: " + serialPort.getBaudRate());
System.out.println("DataBits: " + serialPort.getDataBits());
System.out.println("StopBits: " + serialPort.getStopBits());
System.out.println("Parity: " + serialPort.getParity());
System.out.println("FlowControl: " + serialPort.getFlowControlMode());
this.in = serialPort.getInputStream();
this.out = serialPort.getOutputStream();
write("\n");
int b = -1;
while((b=this.in.read())!=-1) {
System.out.println("data: "+b);
}
}
}
} catch (Exception e) {
System.out.println("Exception: "+e.getMessage());
return false;
}
private void write(String command) {
try {
this.out.write(command.getBytes());
this.out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
什么都没打印出来。任何想法都赞赏!