Can FileInputStream.read read an odd number of bytes?

78 Views Asked by At

I have a method that reads a 16 bit WAVE file, like this:

FileInputStream in = new FileInputStream(file);
byte[] bytes = new byte[8*Number];
do {
    readSize = in.read(bytes, 0, 8*Number);
    ...
} while (...);

I then need to convert each pair of bytes in bytes[] into a short. That is, I better be sure that readSize is even! I know that readSize is not necessarily equal to 8*Number, and that it can be smaller...

Is this parity of readSize somehow guaranteed by the read method, or I must check after the in.read line?

EDIT

Since I also need that readSize to be equal to 8*Number and not just even, I use this workaround, where I am reading once and again until I get all the data I need:

        FileInputStream in = new FileInputStream(f);
        int i, readSize, chunkPerBar = 8*Number;
        byte[] bytes = new byte[chunkPerBar];
        double mean;
        do {
            // If I cannot read *exactly* chunkPerBar bytes, keep adding or exit
            readSize = in.read(bytes, 0, chunkPerBar);
            while ((readSize < chunkPerBar) && (in.available() > 0))
                readSize += in.read(bytes, readSize, chunkPerBar - readSize);
            if (readSize < chunkPerBar) break;  // Discard the last chunk if < chunkPerBar

            mean = 0;
            for (i = 0; i < chunkPerBar / 2; i++) {
                aux = (short)( ( bytes[2*i] & 0xff )|( bytes[2*i+1] << 8 ) );
                mean += aux * aux;
            }

            waveform.drawNewBar(mean/chunkPerBar);
        } while (in.available() > 0);
        in.close();
        } catch {...}
0

There are 0 best solutions below