NFD在传送大量数据的时候,比如我要传输大文件,或者各类文件的时候,只能使用Blob,但是当接收方接收数据的时候,Blob只能转为ByteBuffer,如何转化为byte[]呢?在查看API文档的时候,发现有个array()的函数,但是被坑惨了!!!根本读不出来好嘛!!!
在stackoverflow上找到问题:
If hasArray() reports false then,
calling array() will
throw an exception.
In that case, the only way to get the data in a byte[] is
to allocate a byte[] and
copy the bytes to the byte[] using get(byte) or
similar.
难道阅读纯正的英文文档也有错么T^T
所以,为避免上述的问题,将ByteBuffer转化为byte[]的正确做法是:
ByteBuffer bb =..
byte[] b = new byte[bb.remaining()]; //byte[] b = new byte[bb.capacity()] is OK
</span>
bb.get(b, 0, b.length); //bb.get(b) is OK那么,如何将byte[]转化为ByteBuffer:
byte[] bytes = ......;
ByteBuffer buf = ByteBuffer.wrap(bytes);肘子要加油做毕设!!!
在处理大量数据传输时,如大文件或各种文件,通常使用Blob。然而,接收Blob后,需要将其转化为ByteBuffer。但注意到ByteBuffer的array()方法并不总是可用。如果ByteBuffer是从Heap缓冲区创建的,可以通过array()获取byte[],否则需要通过复制到新的byte[]来实现。StackOverflow上的建议是使用ByteBuffer的get()方法进行转换,以避免抛出异常。
1293

被折叠的 条评论
为什么被折叠?



