我正在尝试调用一个简单的程序 test.exe,它就像 -
int main()
{
int a;
cout<<"Welcome\n";
while(cin>>a&&a!=0)
cout<<"you entered "<<a<<endl;
}
我想从 Java 程序中将其作为进程运行,并从中发送+接收 I/O。我正在使用具有 2 个线程的进程,如下所示-
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Processproblem {
public static void main(String[] args)throws IOException, InterruptedException {
final Process process;
try {
process = Runtime.getRuntime().exec("test.exe");
} catch (IOException e1) {
e1.printStackTrace();
return;
}
new Thread(new Runnable() {
public void run() {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
try {
while ((line = br.readLine()) != null) {
System.out.println("[OUT] " + line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
new Thread(new Runnable() {
public void run() {
try {
byte[] buffer = new byte[1024];
int reading=0;
System.out.println(reading);
BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
while(reading!=-1)
{
reading= System.in.read(buffer);
for(int i = 0; i < buffer.length; i++) {
int intValue = new Byte(buffer[i]).intValue();
if (intValue == 0) {
reading = i;
break;
}
else
{
bw.append((char)intValue);
}
}
bw.newLine();
bw.flush();
}
} catch (Exception e) {
}
}
}
).start();
}
}
但它们没有按预期工作。当我运行该程序时,它只显示“欢迎\n”消息,然后停止输入。当我给出一个整数并在 java 控制台中按 Enter 键时,它什么也不做。
我做错了什么?它们是两个独立的线程,为什么它们会互相阻塞?我的观念有问题吗?
最佳答案
程序等待您的输入。获取进程输出流(使用 getOutputStream)并写入。
关于java - 获取输出并将输入传递给在 java 下运行的执行进程时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6140549/