If data is short[] and you want to write it all to a file, do not use a buffer in memory, write it directly.
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename)); try { oos.writeObject(data); } finally { oos.close(); }
If you write it using an ObjectOutputStream , you will need to read it through an ObjectInputStream , as it not only writes clean data, but also some type information. If you enter short[] , you get back short[] (you can skip these bytes, but you will have to analyze what the stream actually writes). This also applies if your ObjectOutputStream written to ByteArrayOutputStream .
If you don't want to handle this mess, do what ObjectOutputStream basically:
DataOutputStream dos = new DataOutputStream(new FileOutputStream(filename)); try { for (int i = 0; i < data.length; i++) { dos.writeShort(data[i]); } } finally { dos.close(); }
DataOutputStream writes simple data, so you can just read the data directly as byte[] if you want. If byte order matters: it uses Big-Endian.
Since this approach writes single bytes instead of byte[] cartridges, it benefits from using a BufferedOutputStream between them. The default buffer is 8 KB, but it can increase, which can give even better results. Writing data now converts short to byte in memory, and as soon as enough data is available, the entire fragment will be transferred to the low-level functions of the OS to write it.
int bufferSize = 32 * 1024; DataOutputStream dos = new DataOutputStream( new BufferedOutputStream( new FileOutputStream(filename), bufferSize) ); try { for (int i = 0; i < data.length; i++) { dos.writeShort(data[i]); } } finally { dos.close(); }
source share