我用Java編寫一個小應用程序從COM端口讀取,因爲我們使用64個系統我使用RXTX。問題是,當我嘗試運行我的應用程序,我得到以下錯誤:從Java中的COM口,錯誤0x5的閱讀.. RXTX的 src termios.c(892)
"Error 0x5 at ..\rxtx\src\termios.c(892):Access Denied"
想我的代碼,也是從code RXTX網站,任何人都收到任何這方面的經驗嗎?
這裏是我的代碼:
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* This version of the TwoWaySerialComm example makes use of the
* SerialPortEventListener to avoid polling.
*
*/
public class TwoWaySerialComm
{
public TwoWaySerialComm()
{
super();
}
void connect (String portName) throws Exception
{
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
if (portIdentifier.isCurrentlyOwned())
{
System.out.println("Error: Port is currently in use");
}
else
{
CommPort commPort = portIdentifier.open(this.getClass().getName(),2000);
if (commPort instanceof SerialPort)
{
SerialPort serialPort = (SerialPort) commPort;
serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
InputStream in = serialPort.getInputStream();
// OutputStream out = serialPort.getOutputStream();
//
// (new Thread(new SerialWriter(out))).start();
serialPort.addEventListener(new SerialReader(in));
serialPort.notifyOnDataAvailable(true);
}
else
{
System.out.println("Not a serial port...");
}
}
}
public static class SerialReader implements SerialPortEventListener
{
private InputStream in;
private byte[] buffer = new byte[1024];
public SerialReader (InputStream in)
{
this.in = in;
}
public void serialEvent(SerialPortEvent arg0) {
int data;
try
{
int len = 0;
while ((data = in.read()) > -1)
{
if (data == '\n') {
break;
}
buffer[len++] = (byte) data;
}
System.out.print("Result="+new String(buffer,0,len));
}
catch (IOException e)
{
e.printStackTrace();
System.exit(-1);
}
}
}
public static void main (String[] args)
{
try
{
(new TwoWaySerialComm()).connect("COM1");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
你可以改變,只是爲了測試::'而((數據= in.read())> - 1)'in'while while((data = in.read())> 0)' –
當我在連接時拔掉USB-2-COM適配器時,我的控制檯中出現此錯誤垃圾信息。 –