使用FileInputStream和FileOutputStream作为缓冲区

时间:2014-06-01 13:54:49

标签: java buffer fileinputstream fileoutputstream

我想将硬盘用作音频信号的缓冲区。我的想法是将字节形式的样本写入文件,并用另一个线程读取相同的内容。但是,我不得不问FIS.read(byte[]);返回0并给我一个空缓冲区。

这里有什么问题?

这是我写字节的操作:

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

这就是我的读者所做的:

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) {
     //...
}

我使用相同的文件创建bufferOSbufferIS,两者都有效 作者工作,创建文件并在其中包含正确的数据 但是,bufferIS.read(); - 来电始终会返回0 fileInputStream使用buffer.available();返回正确的可用字节数,freeBufferSizeaudioChunk.length等参数是正确的。

在Windows中的同一文件上运行FileInputStreamFileOutputStream是否有问题?

1 个答案:

答案 0 :(得分:2)

您以错误的顺序将参数传递给read来电,应该是:

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

现在您正在传递freeBufferSize作为偏移量来存储read调用的结果,0作为最大读取的字节数。毫不奇怪,如果你告诉read调用最多读取零字节,那么它返回它已读取零字节。

的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