How can I detect and replace newlines in char []?

My application connects to the server using sockets and reads data. Data is no more than four characters long, but sometimes there will be less. The data is added by CR LF compilation, which I do not want to be present at the next stage of processing.

Since I never want to read more than four characters, I have a char[4] buffer. Then, to take into account the time when the data is less than four characters (as well as CR and LF curves), I have the following:

 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 reasonable logging, I see that the loop works as expected, but does not overwrite the characters CR (U + 000d) and LF (U + 000a). I expect the above code to replace any instances of carriage returns or line feeds with "0", but the contents of the buffer will not change.

Honestly, this seems like a clumsy way to do it anyway, so my question is forked:

  • What is wrong with my code? How can I fix it to execute as expected?
  • Is there a better way to do this?
+4
source share
1 answer

It sounds like you better use BufferedReader and its readLine() method to get started:

 BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset)); try { String line; while ((line = reader.readLine()) != null) { processLine(line); } } finally { reader.close(); } 

There are no line separators in the lines here, and you don't need to worry about whether one read call ends halfway through the line, etc.

+4
source

All Articles