简体   繁体   中英

How to invoke cmd commands in from a Java program in Windows?

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. Eg I want to execute javac command on after starting a process for cmd.

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM