我有一个用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();
}
主要思想是在控制台中运行该应用程序并向其发送一些命令。
答案 0 :(得分:0)
因此,经过一些实验,我得到了答案。
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();