在java程序中使用cmd命令

我需要一个java程序,使用cmd命令编译其他java程序

Runtime.exec( -whatever cmd command you need to execute- ) 

http://download.oracle.com/javase/6/docs/api/java/lang/Runtime.html

维诺德。

也许您正在寻找Java Runtime.exec()函数:

 exec public Process exec(String command) throws IOException 

在单独的进程中执行指定的字符串命令。 这是一种方便的方法。 调用exec(command)forms的行为与调用exec(command,null,null)完全相同。

要执行真正的 cmd命令,您需要使用Runtime.exec或类似ProcessBuilder/c选项启动cmd.exe

  String cmd = "dir > t.txt"; ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", cmd); Process process = builder.start(); process.waitFor(); System.out.println("done"); 

要启动像calc.exe这样的可执行文件,您可以直接启动它

  ProcessBuilder builder = new ProcessBuilder("calc.exe"); Process process = builder.start(); process.waitFor(); System.out.println("done"); 

两个代码示例都缺少IO和exception处理……

附加说明:

如果使用JDK1.6,您现在可以使用JavaCompiler以编程方式从另一个Java程序进行编译。 如果您正在尝试实现此目的,则可以从命令行调用编译器程序。

使用cmd可以这样做:

 String cmd = "c:\\Programme\\Ghostgum\\gsview\\gsprint.exe"; //what to execute String prt = "-printer XYZ"; // additional parameters String dat = "\"" + pfad + "\""; // the file to be passed ProcessBuilder pb = new ProcessBuilder(cmd, prt, dat); System.out.println(cmd + " " + prt + " " + dat); pb.redirectErrorStream(true); Process ps = pb.start(); ps.waitFor(); 

不确定为什么要显式调用shell以编译Java程序。 如果你完全确定这是你需要做的事情,那就去做吧,并按照其他人给出的建议。 但是,如果您只想从Java程序中编译Java代码,则可以使用Java 6.0(及更高版本)执行此操作:

http://docs.oracle.com/javase/6/docs/api/javax/tools/JavaCompiler.html

我终于得到了答案。 它实际上编译了一个Java程序。 该计划如下:

 import java.io.BufferedReader; import java.io.InputStreamReader; public class Dos { public static void main(String[] args) { try { String[] command = new String[4]; command[0] = "cmd"; command[1] = "/C"; command[2] = "C:/Program Files/Java/jdk1.6.0_21/bin/javac";//path of the compiler command[3] = "d:\\a.java"; Process p = Runtime.getRuntime().exec(command); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command String s = null; System.out.println("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) { System.out.println(s); } // read any errors from the attempted command System.out.println("Here is the standard error of the command (if any):\n"); while ((s = stdError.readLine()) != null) { System.out.println(s); } System.out.println("I am In try"); } catch (Exception e) { System.out.println("I am In catch"); } } }