Es necesario utilizar el getFloat() y putFloat() comandos en el FloatBuffer del ByteBuffer. De hecho, seguramente deberías hacer esto simplemente por la gran velocidad. Y es algo grandioso de entender por manipulaciones de byte. También puede mezclar y combinar los datos, y ponerlos y obtenerlos según sea necesario. Todo está respaldado por el buffer de byte. Por lo tanto, el hecho común de enviar una matriz, también debe enviar el tamaño de la matriz.
public static void writeFloatArray(float[] array, OutputStream stream) throws IOException {
ByteBuffer buffer = ByteBuffer.allocate(4 * (array.length + 1)).putInt(array.length);
buffer.asFloatBuffer().put(array,0,array.length);
stream.write(buffer.array());
}
Simplemente asegúrese de asignar suficientes bytes para almacenar todo en el búfer. Escribe algunas cosas, escribe otras cosas, etc. Comprender este punto hace las cosas mucho más fáciles. En el otro lado hacemos básicamente la misma cosa, aunque se requiere una lectura adicional, ya que no sabemos qué tan grande es la matriz, sólo que hay una:
public static float[] readFloatArray(InputStream in) throws IOException {
byte[] data = new byte[4];
if (readFully(in, data) != data.length) return null;
int length = ByteBuffer.wrap(data).getInt();
data = new byte[length * 4];
if (readFully(in,data) != data.length) return null;
float[] array = new float[length];
ByteBuffer.wrap(data).asFloatBuffer().get(array,0,array.length);
return array;
}
Y para la funcionalidad completa, aunque no exactamente parte de esta:
public static int readFully(InputStream in, byte[] data) throws IOException {
int offset = 0;
int bytesRead;
boolean read = false;
while ((bytesRead = in.read(data, offset, data.length - offset)) != -1) {
read = true;
offset += bytesRead;
if (offset >= data.length) {
break;
}
}
return (read) ? offset : -1;
}
Respondió muy bien aquí: http://stackoverflow.com/a/19624671/534347 –