I am working on a project and I want to display the contents of a .txt file on the CMD window. I wrote this piece of code to open a demo.txt file on cmd but it does not work. The “path” variable contains the location where the demo.txt file is placed (as you can see obviously).
public static void main(String[] args){ try{ String path = "C:\Users\Hp\Documents\NetBeansProject\Project\build\classes\"; //cmd command to open open the txt file on cmd window String command = ("type " + path + "\demo.txt"); //executing this command on cmd using java Process process = Runtime.getRuntime().exec(command); }catch(IOException e){ e.printStackTrace(); }
This code produces the following output:
Don’t mind the cringey or faulty code as I’m still a beginner in Java programming.
Advertisement
Answer
The executable that displays a CMD window (as you refer to it in your question) is:
C:WindowsSystem32conhost.exe
Use class java.lang.ProcessBuilder
to launch conhost.exe
ProcessBuilder pb = new ProcessBuilder("conhost.exe"); Process proc = pb.start();
When you run this java code a CMD window will be displayed.
Note that you can’t type commands into this window because its standard input is your java program and not the keyboard. However you can send commands to the window from your java code. You simply write to the output stream of the Process
instance.
First get the output stream of the Process
OutputStream os = proc.getOutputStream();
Then write your desired commands to the output stream.
I used the [Windows] start
command to open a separate window – which you can interact with – and ran your desired command in that window. And finally, I closed the window that I opened via conhost.exe
. As a result, the window opened by the start
command remains open and the java program terminates.
Here is the entire code.
import java.io.IOException; import java.io.OutputStream; public class Script { public static void main(String[] args) throws IOException, InterruptedException { ProcessBuilder pb = new ProcessBuilder("conhost.exe"); Process proc = pb.start(); // throws java.io.IOException OutputStream os = proc.getOutputStream(); os.write("start /D C:\Users\Hp\Documents\NetBeansProject\Project\build\classes type demo.txt".getBytes()); // throws java.io.IOException os.write(System.lineSeparator().getBytes()); // throws java.io.IOException os.write("exit".getBytes()); // throws java.io.IOException os.write(System.lineSeparator().getBytes()); // throws java.io.IOException os.flush(); // throws java.io.IOException int status = proc.waitFor(); // throws java.lang.InterruptedException System.out.println("Exit status = " + status); } }