如何同时使用ByteArrayOutputStream和DataOutputStream(Java) [英] how to use ByteArrayOutputStream and DataOutputStream simultaneously (Java)
问题描述
我在这里遇到了很多问题,我认为这是因为我不太了解如何使用Java提供的API。
I'm having quite a problem here, and I think it is because I don't understand very much how I should use the API provided by Java.
我需要将 int
和 byte []
写入 byte []
我想用 DataOutputStream
来解决用 writeInt(int i)
和 write(byte [] b)
,并且为了能够将其放入字节数组中,我应该使用 ByteArrayOutputStream
method toByteArray()。
I thought of using a DataOutputStream
to solve the data writing with writeInt(int i)
and write(byte[] b)
, and to be able to put that into a byte array, I should use ByteArrayOutputStream
method toByteArray().
我明白这个类使用Wrapper模式,所以我有两个选择:
I understand that this classes use the Wrapper pattern, so I had two options:
DataOutputStream w = new DataOutputStream(new ByteArrayOutputStream());
或
ByteArrayOutputStream w = new ByteArrayOutputStream(new DataOutputStream());
但在这两种情况下,我都松散了一种方法。在第一种情况下,我无法访问 toByteArray()
方法,而在第二种情况下,我无法访问 writeInt()
方法。
but in both cases, I "loose" a method. in the first case, I can't access the toByteArray()
method, and in the second, I can't access the writeInt()
method.
我应该如何一起使用这些类?
How should I use this classes together?
推荐答案
像这样:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream w = new DataOutputStream(baos);
w.writeInt(100);
w.write(byteArray);
w.flush();
byte[] result = baos.toByteArray();
实际上你的第二个版本根本不起作用。 DataOutputStream
需要一个实际的目标流来写入数据。你不能做新的DataOutputStream()
。实际上并没有像这样的构造函数。
Actually your second version will not work at all. DataOutputStream
requires an actual target stream in which to write the data. You can't do new DataOutputStream()
. There isn't actually any constructor like that.
这篇关于如何同时使用ByteArrayOutputStream和DataOutputStream(Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!