Read file from serial port using Java

2019-02-13 16:10发布

问题:

I'm begginner in Java, I'm writing ("FLASH").getbytes() like this to serialport.

After I'll get FLASH_OK as response, again I've to send file request. After that I'll get response as FILE_OK then I have read file up to end of the file.

I'm not getting how to do this, so please help me.

Thanks for reply.

回答1:

jSSC is a stable serial IO java library, take a look at following examples:

  • writing data to serial port
  • reading data from serial port


回答2:

Looks like to need a SerialPortReader which needs to implement a SerialPortEventListener

     public void serialEvent(SerialPortEvent event)
     {
            case SerialPortEvent.DATA_AVAILABLE:
            byte[] readBuffer = new byte[40];

            try
            {
                while (inputStream.available() > 0)
                {
                    int numBytes = inputStream.read(readBuffer);
                }
                System.out.print(new String(readBuffer));

                System.out.println();
                System.out.println("DTR: " + serialPort.isDTR());
                System.out.println("DSR: " + serialPort.isDSR());
                System.out.println("CTS: " + serialPort.isCTS());
                System.out.println("RTS: " + serialPort.isRTS());
                System.out.println();
                outputStream.write("ACTIVESYNC".getBytes());
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }