My application connects to a server using sockets and reads data. The data is at most four chars long, but will occasionally be fewer than this. The data is appended by a CR LF combo, which I don’t want to be present for the next step of processing.
Since I never want to read more than four characters, I have a char[4] buffer. Then, to account for the times where the data is less than four chars (and the CR and LF chars creep in), I have this:
for(int i = 0; i < 4; i++) {
String hexString = Integer.toHexString(buffer[i] | 0x10000).substring(1);
if((hexString == "000d") || (hexString == "000a")) {
buffer[i]='0';
}
}
With judicious logging, I can see that the loop performs as expected, but does not overwrite the CR (U+000d) and LF (U+000a) characters. I expect the above code to replace any instances of carriage returns or line feeds with a ‘0’, but the contents of the buffer does not appear to change.
To be honest this feels like a clumsy way of doing this anyway, so my question bifurcates:
- What is wrong with my code? How can I fix it to perform as expected?
- Is there a better way of doing this?
It sounds like you’d be better off using
BufferedReaderand itsreadLine()method to start with:The lines here won’t have the line separators in, and you don’t need to worry about whether a single call to
readends up half way through a line etc.