Java 从 ByteArrayInputStream 获取内部字节数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4315848/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get internal byte array from ByteArrayInputStream
提问by Sean Nguyen
I want to get the internal byte array from ByteArrayInputStream. I don't want to extends that class or write it into another byte array. Is there a utility class that help me do that?
我想从 ByteArrayInputStream 获取内部字节数组。我不想扩展该类或将其写入另一个字节数组。是否有一个实用程序类可以帮助我做到这一点?
Thanks,
谢谢,
采纳答案by Tom Hawtin - tackline
Extend ByteArrayInputStream
, then you have access to the protected
fields. It's the way to do it. Constructors are provided to take the byte array from an argument.
Extend ByteArrayInputStream
,然后您就可以访问这些protected
字段。这是做到这一点的方法。提供构造函数以从参数中获取字节数组。
However, you may find the decorator pattern more helpful.
但是,您可能会发现装饰器模式更有帮助。
回答by Darron
No, access to the internal array is not provided except through the toByteArray() method, which makes a copy.
不,不提供对内部数组的访问,除非通过 toByteArray() 方法进行复制。
回答by Michael Borgwardt
No. Extending the class is the only way (well, that and using reflection to bypass the field visibility, which absolutely NOT recommended).
不。扩展类是唯一的方法(嗯,使用反射绕过字段可见性,绝对不推荐)。
回答by Kurt Kaylor
You can not get access to the same byte array, but you can easily copy the contents of the stream:
您无法访问相同的字节数组,但您可以轻松复制流的内容:
public byte[] read(ByteArrayInputStream bais) {
byte[] array = new byte[bais.available()];
bais.read(array);
return array;
}
回答by Martin Algesten
The internal field is protected, so extending would be easy. If you reallydon't want to, reflection may be another way. This is not a great solution since it relies on internal workings of ByteArrayInputStream (such as knowing the field is called buf
). You have been warned.
内部字段受到保护,因此扩展很容易。如果你真的不想,反思可能是另一种方式。这不是一个很好的解决方案,因为它依赖于 ByteArrayInputStream 的内部工作(例如知道该字段被称为buf
)。你被警告了。
ByteArrayInputStream bis = ...
Field f = ByteArrayInputStream.class.getDeclaredField("buf");
f.setAccessible(true);
byte[] buf = (byte[])f.get(bis);
回答by Vinze
With the library Apache COmmons IO (http://commons.apache.org/io/) you can use the IOUtils.toByteArray(java.io.InputStream input)
使用库 Apache COMmons IO ( http://commons.apache.org/io/),您可以使用IOUtils.toByteArray(java.io.InputStream input)
Edit : ok, I didn't understood the question... no copy... Maybe something like :
编辑:好的,我不明白这个问题......没有副本......也许是这样的:
byte[] buf = new byte[n];
ByteArrayInputStream input = new ByteArrayInputStream(buf);
will allow you to keep a reference to the buffer used by the input stream
将允许您保留对输入流使用的缓冲区的引用