Hi,
I'm having the following problem on netty 4.1.0.CR7:
java.lang.UnsupportedOperationException: direct buffer
at io.netty.buffer.PooledUnsafeDirectByteBuf.array(PooledUnsafeDirectByteBuf.java:343)
at io.netty.buffer.SwappedByteBuf.array(SwappedByteBuf.java:916)
With this code (works fine on other versions):
return new String(msg.readBytes(strLength).array());
msg is a ByteBuf
That is because its a direct buffer and so hasArray() returns false. This is expected as stated in the javadocs
I upgrade netty-all-4.0.36.Final to 4.1.0.Final so that meet the problem.
@normanmaurer How do i get a byte[] from a ByteBuffer now since array(); gives this error?
Thanks
The ByteBuf interface offers readBytes(byte[] dst); and getBytes(int index, byte[] dst); which will copy the data to a byte[] if that is what you need. See the javadocs in ByteBuf for more info.
If you use kotlin you can make an extension and use that instead
fun ByteBuf.toByteArraySafe(): ByteArray {
if (this.hasArray()) {
return this.array()
}
val bytes = ByteArray(this.readableBytes())
this.getBytes(this.readerIndex(), bytes)
return bytes
}
Hi, you can use that instead
new String(ByteBufUtil.getBytes(buf), Charset.forName("UTF-8"))
Most helpful comment
Hi, you can use that instead
new String(ByteBufUtil.getBytes(buf), Charset.forName("UTF-8"))