我有一个用 c 编写的控制台应用程序,它在控制台中运行并有自己的伪控制台。通过它,我配置了这个应用程序并运行它。一切都好。现在我试图在 Java 应用程序中运行这个应用程序,但我遇到了问题。例如,我使用 sh
ProcessBuilder builder = new ProcessBuilder("sh");
builder.redirectErrorStream(true);
Process process = builder.start();
try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()))) {
bw.write("echo lol");
while (true) {
// System.out.println(process.isAlive());
if (br.ready()) {
System.out.println(br.readLine());
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
主要思想是在控制台中运行应用程序并向其发送多个命令。
所以,经过几次实验,我得到了答案。
ProcessBuilder builder = new ProcessBuilder("sh");
Process process = builder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
new Thread(new Runnable() {
public void run() {
Scanner scan = new Scanner(br);
while (true) {
try {
if (!br.ready()) break;
System.out.println(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();
PrintWriter bw = new PrintWriter(process.getOutputStream());
bw.println("echo Hello World");
bw.println("echo lol");
bw.flush();
bw.close();
我是一名优秀的程序员,十分优秀!