Is there a way to open a cmd.exe
via ProcessBuilder
and then reference its streams such that one could call NewProcessOutputStream.println()
and Scanner s = new Scanner(NewProcessInputStream)
?
I am aware that I can issue a command such as cmd /c dir
and read the input stream, but I would like to open the cmd
process, then access its streams such that I can print to it whenever.
Is what I am thinking of possible? Or should I be executing another program via the process?
Edit (Updated): Output not what expected
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();
}
}
Output:
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>
Yes, you can get the process input using Process.getOutputStream()
and its output using Process.getInputStream()
.
Here's an example:
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();
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.