1

Part of my code:

byte[] bytes = new byte[8000];
final DataInputStream in = new DataInputStream(s.getInputStream());
final int input = in.read(bytes);

I don't know how many bytes will come to me. Can I do unlimited array? Which way is the best in this situation?

Mat
  • 202,337
  • 40
  • 393
  • 406
Ilya
  • 29,135
  • 19
  • 110
  • 158

2 Answers2

1

Much better to use ByteBuffer if you are using a version of Java that supports it

ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
1

You don't know how much data will be available when you read. E.g. if the last time the socket was written to was 16KB for example, you might read less than this or more than this.

You have to write code which assumes you don't need to know. This allows you to prcess data as it arrives regardless of length.


If you are expecting to send a fixed length block of data, send the size first.

byte[] bytes = new byte[1024];
final DataInputStream in = new DataInputStream(s.getInputStream());

int length = in.readInt();
if (length > bytes.length) bytes = new byte[length];
in.readFully(bytes, 0, length); // read length bytes or throw an exception.
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130