Reputation: 18171
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;
}
Upvotes: 0
Views: 1922
Reputation: 11
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);
}
Upvotes: 1
Reputation: 129
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;
Upvotes: 0