I’m creating a mobile app to run on a phone and trying to read data from it in the most efficient way. The application will send data to my server app (in the form of bytes, not necessarily characters).
I won’t know the length of the data; the end will be marked with a 3 byte marker (i.e. 0x11,0x22,0x33), and then a new set of data will be sent. It is likely that a large amount of data will be sent in each “set” of data. I’m wondering, then, what the most efficient way to read this data is. Should I use InputStreamReader? BufferedReader? Obviously, I will need to inspect each character to see if it is part of the marker, and if so, send all the data before the marker to another method for processing.
From what I can tell, BufferedReader.readLine() would be what I want if my end marker was a \n (obviously, this is not the case). Do I need to write my own method to read a BufferedReader byte-by-byte and look for my marker? (I also do not know if this would be the most efficient way?)
Assuming that your data is byte data rather than character data, you should wrap your socket input stream in a
BufferedInputStream, and use that to read the data one byte at a time, saving the bytes in a byte buffer of some kind. (One option is to use aByteArrayOutputStreamto buffer the data bytes that you’ve read from theBufferedInputStream.)BufferedReaderandreadLine()are NOT the way to go:readLinemethod only understands lines separated by'\n'and/or'\r'characters. There’s no way to get it to understand other “line” separators.Finally, note that the
BufferedInputStreamis very important for performance reasons. If you don’t use one, and read from the socket InputStream one byte at a time, you are likely to incur a significant performance hit due to the number of syscalls that your Java app performs.