ruhig brauner
ruhig brauner

Reputation: 963

use FileInputStream and FileOutputStream as a buffer

I would like to use the hard drive as a buffer for audio signals. My Idea was to just write the samples in byte form to a file, and read the same with another thread. However, I have to problem that FIS.read(byte[]); returns 0 and gives me an empty buffer.

What is the problem here?

This is my operation for writing bytes:

try {       
        bufferOS.write(audioChunk);
        bufferOS.flush();
} catch (IOException ex) {
       //...
}        

And this is what my reader does:

byte audioChunk[] = new byte[bufferSize];
int readBufferSize;
int freeBufferSize =  line.available(); // line = audioline, available returns free space in buffer

try {            
    readBufferSize = bufferIS.read(audioChunk,freeBufferSize, 0);

} catch(IOException e) {
     //...
}

I create both bufferOS and bufferIS with the same file, both work.
The writer works, the file gets created and has the correct data in it.
However the bufferIS.read();-call always returns 0.
The fileInputStream returns the correct amount of available bytes with buffer.available(); and parameters like freeBufferSize and audioChunk.length are correct.

Is there a problem with running FileInputStream and FileOutputStream on the same file in windows?

Upvotes: 0

Views: 331

Answers (1)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31269

You're passing the arguments in the wrong order to the read call, it should be:

readBufferSize = bufferIS.read(audioChunk, 0, freeBufferSize);

Right now you're passing freeBufferSize as the offset to store the result of the read call and 0 as the number of bytes to read at maximum. It's not surprising that, if you tell the read call to read at most zero bytes, that it returns that it has read zero bytes.

Javadoc:

 * @param      b     the buffer into which the data is read.
 * @param      off   the start offset in array <code>b</code>
 *                   at which the data is written.
 * @param      len   the maximum number of bytes to read.
 * @return     the total number of bytes read into the buffer, or
 *             <code>-1</code> if there is no more data because the end of
 *             the stream has been reached.
public abstract class InputStream implements Closeable {
    // ....
    public int read(byte b[], int off, int len) throws IOException

Upvotes: 2

Related Questions