简体   繁体   English

将DataOutputStream以“动态”大小写入ByteArray / ByteBuffer中吗?

[英]Write DataOutputStream in ByteArray / ByteBuffer with “dynamic” size?

i ask myself if there is a nice solution for receiving data via TCP and reading the data in a DataInputStream and store the data in a bytearray of "dynamic" size. 我问自己是否有一个很好的解决方案,可以通过TCP接收数据并在DataInputStream中读取数据,并将数据存储在“动态”大小的字节数组中。 I thought about some solutions like writing in buffers and finally store it in a created array that is as large as the packet i received. 我考虑过一些解决方案,例如写入缓冲区,最后将其存储在创建的数组中,该数组与我收到的数据包一样大。

Here an example: the data i receive via TCP (byte by byte) is n*13 Byte large and the end of a packet is 13 Bytes of zeros (13 Byte of zeros are unique, cant be in the data before). 这是一个例子:我通过TCP接收的数据(逐字节)为n * 13字节,数据包的末尾为13字节的零(13字节的零是唯一的,之前不能在数据中)。 The next packet is m*13 Byte + 13 Byte of zeros and so on. 下一个数据包是m * 13字节+ 13字节的零,依此类推。 So i want to listen to the stream and store eg n*13 Byte in a bytearray without zeros (i dont know the size of one dataset before). 因此,我想收听流并将n * 13字节存储在不带零的字节数组中(我之前不知道一个数据集的大小)。

Can you tell me how to do it a slim way? 你能告诉我如何瘦身吗?

Thanks in advance! 提前致谢!

Chris 克里斯

I would read the data straight into a direct ByteBuffer. 我会将数据直接读取到直接的ByteBuffer中。 You don't need a DataInputStream as well. 您也不需要DataInputStream。 I would have the ByteBuffer larger than needed eg 1 MB or 10 MB and use the fact that unused direct buffers (like unused native memory) only uses virtual memory, not real memory. 我将使ByteBuffer大于所需的大小,例如1 MB或10 MB,并使用未使用的直接缓冲区(例如,未使用的本机内存)仅使用虚拟内存而非实际内存的事实。 I would make sure this buffer is re-used as much as possible, ideally for the life of the application. 我将确保尽可能多地重用此缓冲区,理想情况下应在应用程序的整个生命周期内都将其重用。

In a 64-bit environment you can make the buffers really large. 在64位环境中,可以使缓冲区很大。 eg 1 GB without much impact. 例如1 GB,影响不大。

If you want to minimise memory consumption, I would process the data as you receive it. 如果要最大程度地减少内存消耗,我将在收到数据时对其进行处理。 That way you avoid having to store it first. 这样,您就不必先存储它。 It sounds like the minimum size is 13 bytes and would make a reasonable buffer size like 512 bytes or 2 KB. 听起来最小的大小是13个字节,并且可以使缓冲区大小合理,例如512个字节或2 KB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM