0

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.

2
  • 1
    cmd /c ... to execute other apps... Commented Dec 1, 2015 at 14:45
  • 1
    Possible duplicate of Start CMD by using ProcessBuilder Commented Dec 1, 2015 at 14:46

1 Answer 1

0
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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.