1

我想将字节数组写入OutputStream串行端口,但出现错误“java.IO.Exception”。

以下是我尝试编写的数组:

byte[] b = new byte[255] {127, -112, 17, 126, -100, 76, 98, 68, -48, -94, 51,
                          -36, -32, -40, -79, -114, -69, 67, 51, 69, 33, 83, 0,
                          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,...}

以下方法打开并写入端口:

public boolean OpenSSPComPort(SSP_COMMAND cmd){
    try
    {
        CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(cmd.ComPort);
        if ( portIdentifier.isCurrentlyOwned() )
        {
            System.out.println("Error: Port is currently in use");
        }
        else
        {
            comPort = (SerialPort) portIdentifier.open("Open Port",2000);
            if ( comPort instanceof SerialPort )
            {
                SerialPort serialPort = (SerialPort) comPort;
                serialPort.setSerialPortParams(9600,SerialPort.DATABITS_8,SerialPort.STOPBITS_2,SerialPort.PARITY_NONE);
                in = serialPort.getInputStream();
                out = serialPort.getOutputStream();
                serialPort.addEventListener(this);
                serialPort.notifyOnDataAvailable(true);

                in = comPort.getInputStream();
                out = comPort.getOutputStream();

                comPort.addEventListener(this);
                comPort.notifyOnDataAvailable(true);
            }
            else
            {
                System.out.println("Error: Only serial ports are handled by this example.");
            }

            System.out.println("Roshan:Port open successfull");
        }
    }
    catch (Exception ex)
    {
         lastException = ex;
         return false;
    }

    return true;
}

public boolean WritePort()
{
    try
    {
        byte[] byteArray = new byte[ssp.txData.length];
        for(int i = 0; i<ssp.txData.length; i++)
            byteArray[i] = (byte) ssp.txData[i];
        System.out.println("array to write"+Arrays.toString(byteArray));
        out.write(byteArray, 0, byteArray.length);  //here gets the IOException
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
        return false;
    }
    return true;
}

这是完整的堆栈跟踪:

java.io.IOException
    at gnu.io.RXTXPort$SerialOutputStream.write(RXTXPort.java:1159)
    at dllUtilities.SSPComms.WritePort(SSPComms.java:685)
    at dllUtilities.SSPComms.SSPSendCommand(SSPComms.java:161)
    at hopper.CHopper.SendCommand(CHopper.java:120)
    at hopper.CHopper.SetProtocolVersion(CHopper.java:783)
    at gui.Form1.ConnectToValidator(Form1.java:376)
    at gui.Form1.MainLoop(Form1.java:235)
4

1 回答 1

0

可能是你写得太快了。您是否尝试将波特率设置得更高,或者写得更慢。它仍然一次调试一个字节吗?

于 2013-03-16T09:03:34.550 回答