我正在编写一些涉及使用 ByteBuffers 的简单网络代码。出于某种原因,以下代码在我的两个测试设备上引发了 UnsopportedOperationException:
int send = Integer.parseInt(edtxt.getText().toString());
OutputStream out = sock.getOutputStream();
ByteBuffer buf = ByteBuffer.allocateDirect(1);
buf.order(ByteOrder.BIG_ENDIAN);
buf.put((byte)send);
buf.rewind();
byte[] outa = buf.array(); //Exception thrown here
out.write(outa);
它失败的两个设备是:
运行 Android 2.3.3 的索尼爱立信 Xperia Play
运行 Android 2.3.5 的 Motorla Droid X2
它适用的两个是:
运行 Android 4.4.2 的 LG G3
运行 Android 4.4.4 的 Nexus 4
文档说如果字节缓冲区不基于数组,则会抛出 UnsupportedOperationException 。这是我只需要处理的 Gingerbread 和 KitKat 之间的区别,还是只是一种不良做法?