【问题标题】:I/O output depending on reader's buffer sizeI/O 输出取决于阅读器的缓冲区大小
【发布时间】:2011-10-04 22:22:12
【问题描述】:

这是对我之前的问题here 的跟进。

当我使用大小为 1024 * 32 的示例中的字节数组时,应该是波形文件的结果文件太晚了。 如果我使用较小的尺寸,比如只有 32 个字节,或者甚至使用单个字节,比如

fstr.write(this.stream.read());

效果很好。

以下代码:

import java.io.*;

class ErrorThread extends Thread {
    InputStream stream = null;

    public ErrorThread(InputStream stream) {
    this.stream = stream;
    }

    public void run() {
    try {
        byte[] buf = new byte[32 * 1024];
        int nRead = 0;
        while ((nRead = this.stream.read()) != -1) {

        }
        this.stream.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    }
}

class InputThread extends Thread {
    InputStream stream = null;

    public InputThread(InputStream stream) {
    this.stream = stream;
    }

    public void run() {
    try {
        FileOutputStream fstr = new FileOutputStream("test.wav");
        int nRead = 0;
        byte[] buf = new byte[1024 * 32];
        while ((nRead = this.stream.read(buf, 0, buf.length)) != -1) {
        fstr.write(buf, 0 , buf.length);
        }
        this.stream.close();
        fstr.close();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    }
}

public class Test {
    public static void main(String[] args) {
    try {
        Process p = new ProcessBuilder("lame", "--decode", "test.mp3", "-").start();
        ErrorThread et = new ErrorThread(p.getErrorStream());
        InputThread it = new InputThread(p.getInputStream());
        et.start();
        it.start();
        p.waitFor();
    }
    catch (Exception e) {
        e.printStackTrace();
    }
    }
}

【问题讨论】:

    标签: java inputstream processbuilder


    【解决方案1】:
        fstr.write(buf, 0 , buf.length);
    

    应该是

        fstr.write(buf, 0 , nRead);
    

    如果输入不是 32K 的倍数,则您正在将缓冲区中的剩余部分写出。

    【讨论】:

      猜你喜欢
      • 2020-06-30
      • 2015-08-20
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多