[英]How to get number of bytes?
How do I obtain the number of bytes before allocating the byte size of the array 'handsize' as shown below as the incoming ByteArray data are sent in 3 different sizes. 在分配数组'handsize'的字节大小之前,如何获得字节数,如下所示,因为传入的ByteArray数据以3种不同的大小发送。 Thanks.
谢谢。
BufferedInputStream bais = new
BufferedInputStream(requestSocket.getInputStream());
DataInputStream datainput = new DataInputStream(bais);
//need to read the number of bytes here before proceeding.
byte[] handsize = new byte[bytesize];
datainput.readFully(handsize);
You could use a ByteArrayOutputStream , then you wouldn't have to worry about it. 您可以使用ByteArrayOutputStream ,那么您不必担心它。
ByteArrayOutputStream out = new ByteArrayOutputStream();
//write data to output stream
byte[] bytes = out.toByteArray();
There's no way to know how many bytes of data are yet to be received on a socket--knowing this would be tantamount to clairvoyance. 无法知道要在套接字上接收多少字节的数据-知道这将等于透视。 If you're using your own protocol for client/server communication, you could send the number of bytes of data as an integer, before sending the actual bytes themselves.
如果您使用自己的协议进行客户端/服务器通信,则可以在发送实际字节本身之前,将数据字节数作为整数发送。 Then the receiving side would know how many bytes to expect.
然后,接收方将知道期望多少字节。
As has been pointed out, the problem as stated is impossible. 如已经指出的,所述问题是不可能的。 But why do you need to know?
但是你为什么要知道? Why not store the data in a variable size structure, like an ArrayList, as you read it?
为什么不在读取数据时将数据存储在可变大小的结构(如ArrayList)中? Or maybe even process it as you read?
或者甚至在阅读时进行处理?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.