Reputation: 83
I want to create an application which can compile and run external programs. For this I need to run compiler commands from the command prompt (commands like javac and gcc). I tried the approach given here - Run cmd commands through java
This is my code
import java.io.*;
public class Main
{
public static void main(String[] args) throws Exception
{
ProcessBuilder builder=new ProcessBuilder(
"cmd.exe","javac F://Test.java","java -cp F:// Test");
builder.redirectErrorStream(true);
builder.start();
Process p = builder.start();
BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
try
{
while (true)
{
line = r.readLine();
if (line != null)
System.out.println(line);
}
}
catch(Exception e){}
}
}
But when I run it, it just executes the 1st command (cmd.exe), displays this output :
Microsoft Windows [Version 6.3.9600] (c) 2013 Microsoft Corporation. All rights reserved.
And then it waits indefinitely. What am I doing wrong here?
EDIT- My question was identified as the duplicate of this question - Start CMD by using ProcessBuilder . But I believe that question asks for how to start cmd from java code. I need my program to execute cmd commands as well. E.g. I want to execute javac command on after starting a process for cmd.
Upvotes: 0
Views: 358
Reputation: 409
Process p = Runtime.getRuntime().exec("gcc ...");
https://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html#exec(java.lang.String)
You should also read this post:
Want to invoke a linux shell command from Java
Most of it isn't Linux specific. It contains useful info about how to handle standard-error or stream redirection (which is also possible in windows shell).
Upvotes: 0