简体   繁体   English

如何获得字节数?

[英]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.

相关问题 如何获取使用 OkHttp3 传输的实际字节数? - How can I get the number of actual bytes transferred with OkHttp3? 如何获得确切的字节数? - How to get the exact bytes? 获取Java InputStream后面文件的字节数 - Get the number of bytes of a file behind a Java InputStream 如何从文件中读取特定数量的字节到Java中的bytes数组中? - How to read a specific number of bytes from a file into a bytes array in Java? 如何使用文件输入和输出流从文件中添加和获取特定数量的字节? - How to add and get specific number of bytes from a file using file input and output streams? 我如何才能在Java与一堆过时的Swift代码中获得相同数量的字节? - How can I get the same number of bytes in Java vs a tad outdated Swift code? 如何获取FileChannel.transferFrom在写入过程中写入的字节数 - How to get number of bytes that FileChannel.transferFrom wrote during it's writting 当你有奇数个字节时,如何从ByteBuffer(Little Endian)得到一个长的? - How to get a long from a ByteBuffer (Little Endian) when you have odd number of bytes? 如何查找传递给函数的参数的字节数? - How to find the number of bytes of parameters passed to the function? 如何知道二进制文件的字节数? - How to know number of bytes of a Binary File?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM