简体   繁体   English

如何从Java中的DataInputStream读取可变大小的byte []?

[英]How to read byte[] of variable size from DataInputStream in Java?

I'm working on a TCP server project and I need to transfer a file via a byte[] using a DataOutputStream and a DataInputStream and I've gotten stuck. 我正在处理一个TCP服务器项目,我需要使用DataOutputStream和DataInputStream通过byte []传输文件,但是我被卡住了。 I'm able to write the byte array to the output stream with no problems, but I was looking at the documentation for the DataInputStream and the method that it seems I would want is read(byte[] b). 我可以毫无问题地将字节数组写入输出流,但是我正在查看DataInputStream的文档,而看来我想要的方法是read(byte [] b)。 The issue is that this requires I create a byte[] beforehand, but I don't necessarily know what the size it needs to be so I need some help on how I should go about doing this. 问题是这要求我事先创建一个byte [],但我不一定知道它的大小,因此我需要一些有关如何执行此操作的帮助。

Take a look at Apache Commons IO library . 看一下Apache Commons IO It has a utility class called IOUtils which can read an entire input stream into byte array without you having to declare a byte [] beforehand. 它具有一个称为IOUtils的实用程序类,它可以将整个输入流读入字节数组,而无需事先声明byte []。 For more information look at this 欲了解更多信息,请看这里

You don't. 你不知道 All you need is the standard Java copy loop: 您只需要标准的Java复制循环即可:

byte[] buffer = new byte[8192]; // or wherever you like > 0
int count;
while ((count = in.read(buffer)) > 0)
{
    out.write(buffer, 0, count);
}

I made a library for TCP server and client. 我为TCP服务器和客户端创建了一个库。 You might as well use it. 您不妨使用它。 GitHub GitHub上

It is not much, but it is simple. 它不多,但是很简单。

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

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