Reputation: 23
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
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