有没有办法通过cmd.exe
打开ProcessBuilder
,然后引用其流,以便可以拨打NewProcessOutputStream.println()
和Scanner s = new Scanner(NewProcessInputStream)
?
我知道我可以发出cmd /c dir
之类的命令并读取输入流,但我想打开cmd
进程,然后访问其流,以便我可以打印到它每当。
我在想什么?或者我应该通过这个过程执行另一个程序吗?
编辑(更新):输出不是预期的
import java.io.*;
import java.util.*;
public class Terminal {
public static void main(String[] args) throws IOException {
Process cmd = new ProcessBuilder("cmd").start();
PrintWriter writer = new PrintWriter(cmd.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
writer.println("Hello");
writer.println("World!");
writer.println("How are you?");
writer.close();
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
}
}
输出:
C:\Users\Paul\Desktop\temp\CLI\src>java Terminal
Microsoft Windows [Version 10.0.15063]
(c) 2017 Microsoft Corporation. All rights reserved.
C:\Users\Paul\Desktop\temp\CLI\src>Hello
C:\Users\Paul\Desktop\temp\CLI\src>World!
C:\Users\Paul\Desktop\temp\CLI\src>How are you?
C:\Users\Paul\Desktop\temp\CLI\src>
C:\Users\Paul\Desktop\temp\CLI\src>
答案 0 :(得分:0)
是的,您可以使用Process.getOutputStream()
使用Process.getInputStream()
获取流程输入。
以下是一个例子:
public class ProcessTest {
public static void main(String[] args) throws IOException {
Process grep = new ProcessBuilder("grep", "foo").start();
PrintWriter writer = new PrintWriter(grep.getOutputStream());
BufferedReader reader = new BufferedReader(new InputStreamReader(grep.getInputStream()));
writer.println("this is the first line");
writer.println("this is the foo line");
writer.println("this is the last line");
writer.println("nope, another foo");
writer.close();
// EDIT: fixed end of stream check
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
}
}