【问题标题】:use FileInputStream and FileOutputStream as a buffer使用 FileInputStream 和 FileOutputStream 作为缓冲区
【发布时间】:2014-06-01 13:54:48
【问题描述】:

我想将硬盘驱动器用作音频信号的缓冲区。我的想法是将样本以字节形式写入文件,然后用另一个线程读取相同的内容。但是,我不得不质疑 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();-call 总是返回0
fileInputStream 使用 buffer.available(); 返回正确的可用字节数,freeBufferSizeaudioChunk.length 等参数是正确的。

在 windows 的同一个文件上运行 FileInputStreamFileOutputStream 有问题吗?

【问题讨论】:

  • 读写器在同一个JVM进程中?
  • 它是一个应用程序,但线程不同。 (reader变成自己的线程,writer由主线程执行)
  • 好的,作者如何通知读者?以及如何向读者指示文件中数据的偏移量和长度?
  • 它们彼此独立运行。每当作者获得新的音频字节时,作者都会在文件中写入音频字节。读者在几毫秒之间循环读取他需要多少。如果没有足够的字节,他就读多少就读多少。这完全是一个数据队列,存在旧字节未被丢弃的问题。

标签: java buffer fileinputstream fileoutputstream


【解决方案1】:

您以错误的顺序将参数传递给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

【讨论】:

    猜你喜欢
    • 2019-06-01
    • 1970-01-01
    • 2011-11-17
    • 1970-01-01
    • 2013-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多