0

Wondering regarding code below that reads data from TCP Socket BufferedInputStream. Is there any reason read first byte with int s = _in.read() and later rest ones _in.read(byteData);. Can I read just byte[] without using first read line?

private static String readInputStream(BufferedInputStream _in) throws IOException 
{
    String data = "";
    int s = _in.read();
    if(s==-1)
        return null;
    data += ""+(char)s;
    int len = _in.available();
    System.out.println("Len got : "+len);
    if(len > 0) {
        byte[] byteData = new byte[len];
        _in.read(byteData);
        data += new String(byteData);
    }
    return data;
}
vico
  • 13,725
  • 30
  • 108
  • 237
  • 2
    It's probably trying to populate the buffered cache by first reading one byte (otherwise the call to `available()` would return 0). That's probably a misuse of the `available()` method as it's not generally recommended to use the value returned by `available()` to determine the size of the buffer to read into. – DodgyCodeException Apr 26 '19 at 16:14
  • See also: https://stackoverflow.com/questions/309424/how-do-i-read-convert-an-inputstream-into-a-string-in-java – DodgyCodeException Apr 30 '19 at 10:30

2 Answers2

1

You should not rely on calling available() to find out the Stream's length as it returns only estimation. If you want to read all bytes, do it in a loop like this:

String data = "";
byte[] buffer = new byte[1024];
int read;
while((read = _in.read(buffer)) != -1) {
   data += new String(buffer, 0, read);    
} 
  • It would be better to use StringBuilder. Also, there's InputStream.readAllBytes() which would give you all the bytes without needing to write a loop, but unfortunately is only available from Java 9 onwards. – DodgyCodeException Apr 29 '19 at 10:49
0

You can use skip method of BufferedInputStream to skip anynumber of bytes as you want. Like you can add into your code as following

 _in.skip(1);
  int len = _in.available();
  System.out.println("Len got : "+len);
  if(len > 0) {
    byte[] byteData = new byte[len];
    _in.read(byteData);
    data += new String(byteData);
 }
return data;
sandip
  • 79
  • 4
  • But the original method is not skipping any bytes. – DodgyCodeException Apr 26 '19 at 16:09
  • I asked in wrong way. I need to read all bytes. And I would like do that in simpler way, without using line `int s = _in.read();`. I'm also wondering what is the reason of using this line. – vico Apr 26 '19 at 16:13