我启动了一个通过 SyncPipe Runnable 输出到 System.out 的 cmd 应用程序:
public class SyncPipe implements Runnable {
private final InputStream is;
private final OutputStream os;
public SyncPipe(InputStream is, OutputStream os) {
this.is = is;
this.os = os;
}
public void run() {
try {
final byte[] buffer = new byte[1024];
for ( int length = 0; ( length = is.read(buffer) ) != -1; )
os.write(buffer, 0, length);
System.out.print("stopped");
} catch ( Exception ex ) {
ex.printStackTrace();
}
}
}
我开始 RunItcmd = "C:/bin/read.exe -f D:/test.jpg"
private class RunIt implements Runnable {
public int p;
public String cmd;
public RunIt (int p, String cmd) {
this.p = p;
this.cmd = cmd;
}
public void run() {
ProcessBuilder pb = new ProcessBuilder("cmd");
try {
process = pb.start();
(new Thread(new SyncPipe(process.getErrorStream(), System.err))).start();
(new Thread(new SyncPipe(process.getInputStream(), System.out))).start();
OutputStream out = process.getOutputStream();
out.write((cmd + "\r\n").getBytes());
out.flush();
out.close();
try {
process.waitFor();
} catch ( InterruptedException e ) {
e.printStackTrace();
}
println("Stopped using %d.", p);
} catch ( IOException ex ) {
ex.printStackTrace();
}
}
}
我现在的问题是:我怎样才能(new Thread(new SyncPipe(process.getErrorStream(), System.err)))
死?给 SyncPipe 一个布尔变量stop
,在运行时设置它true
,并通过检查它for ( int length = 0; ( length = is.read(buffer) ) != -1 && !stop; )
并没有成功。
提前非常感谢。
我最终完成了@Gray 建议的解决方法。它现在有效:
public void run() {
try {
final byte[] buffer = new byte[1024];
do
if ( is.available() > 0 ) {
int length = is.read(buffer);
if ( length != -1 )
os.write(buffer, 0, length);
else
stop = true;
}
while ( !stop );
} catch ( Exception ex ) {
ex.printStackTrace();
}
}