You need to use the getFloat () and putFloat () commands in the FloatBuffer ByteBuffer. In fact, you should do this simply because of sheer speed. And this is great to understand for manipulating bytes. You can also mix and match data, and add and receive them as needed. All this is supported by byte buffer. So, the usual thing is to send an array, you also need to send the size of the array.
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()); }
You just allocate enough bytes to store everything in the buffer. Write some things, write some other materials, etc. Understanding this point simplifies the job. On the reverse side, we basically do the same thing, although we need additional reading because we donβt know how large the array is, only one:
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; }
And for full functionality, although not quite from this:
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; }
Tatarize
source share