gpt4 book ai didi

java - I/O 输出取决于读卡器的缓冲区大小

转载 作者:行者123 更新时间:2023-12-01 15:43:13 25 4
gpt4 key购买 nike

这是我之前的问题 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();
}
}
}

最佳答案

    fstr.write(buf, 0 , buf.length);

应该是

    fstr.write(buf, 0 , nRead);

如果输入不是 32K 的倍数,则将缓冲区中的剩余内容写出。

关于java - I/O 输出取决于读卡器的缓冲区大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7654705/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com