我正在尝试使用 Linux 下的 ProcessBuilder 类将 mp3 文件解码为 wav 文件。由于某种原因,该过程没有停止,因此我必须手动取消它。
有人可以给我一些提示吗?我认为引用的代码很容易重现:
import java.io.*;
public class Test {
public static void main(String[] args) {
try {
Process lameProcess = new ProcessBuilder("lame", "--decode", "test.mp3", "-").start();
InputStream is = lameProcess.getInputStream();
FileOutputStream fileOutput = new FileOutputStream("test.wav");
DataOutputStream dataOutput = new DataOutputStream(fileOutput);
byte[] buf = new byte[32 * 1024];
int nRead = 0;
int counter = 0;
while((nRead = is.read(buf)) != -1) {
dataOutput.write(buf, 0, buf.length);
}
is.close();
fileOutput.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
jstack的输出
"main" prio=10 tid=0x0000000002588800 nid=0x247a runnable [0x00007f17e2761000]
java.lang.Thread.State: RUNNABLE
at java.io.FileInputStream.readBytes(Native Method)
at java.io.FileInputStream.read(FileInputStream.java:236)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
- locked <0x00000000eb5b1660> (a java.io.BufferedInputStream)
at java.io.FilterInputStream.read(FilterInputStream.java:107)
at Test.main(Test.java:17)
最佳答案
您需要排出进程的输出流(通过 getInputStream()
)和错误流(通过 getErrorStream()
),否则可能会阻塞。
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.
(适用于错误流和输出流)
您可能需要在不同的线程中排出每个流,因为每个流在没有数据时可能会阻塞。
关于java - ProcessBuilder 不会停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7561503/