falcon2303
falcon2303

Reputation: 23

How Can I found out what is length of recieved message on serial port?

InputStream inputFromPort;

    try {
        inputFromPort = serial.getInputStream();  //SerialPort

        b=new byte[20];

        inputFromPort.read(b);

        reading=new String(b,"UTF-8");

        System.out.println(reading.length());

        System.out.println("new message: " + reading);

        inputFromPort.close();

        serial.close();         
    } 

RESULT: new message: Hello, world! -> which is OK six boxes symbols ->(which I can't copy here)I know that they appear 'cause length of b is larger then "Hello,world!",it would be great if somehow I know size of recieved message so I can initialize byte array b on that size

Upvotes: 2

Views: 64

Answers (1)

Cyrille Ka
Cyrille Ka

Reputation: 15533

Check the return value of inputFromPort.read(b);:

 int readLength = inputFromPort.read(b);

Then you have to create your string with only the bytes received, that is the part of the byte array that was actually written by the call to read():

String reading = new String(b, 0, readLength, "UTF-8");

This way you won't have "boxes symbols" after the the "Hello, World!"

Upvotes: 2

Related Questions