如何在另一个java程序中使用cmd打开/运行java程序

如何在另一个java程序中使用cmd打开/运行java程序,java,Java,我想通过使用另一个Java程序在cmd中生成一个Javac命令来编译Java程序,然后运行它。我该怎么做?有我可以使用的类吗 例如,这里是cmd C:\Users\UserName\Documents>Javac HelloWorld.java 如何在java程序中编译HelloWorld.java,然后运行它 这是我的初始源代码,其中有一个目录和一个Java文件 public class Test { public static void main(String[] args) {

我想通过使用另一个Java程序在cmd中生成一个Javac命令来编译Java程序,然后运行它。我该怎么做?有我可以使用的类吗

例如,这里是cmd C:\Users\UserName\Documents>Javac HelloWorld.java

如何在java程序中编译HelloWorld.java,然后运行它

这是我的初始源代码,其中有一个目录和一个Java文件

public class Test {

    public static void main(String[] args) {
        String directory = "C:\\Users\\UserName\\Documents";
        String fileName = "HelloWorld.java";
    }
}
试试这个

try {
    // Execute command
    String command = "cmd /c start cmd.exe";
    Process child = Runtime.getRuntime().exec(command);

    // Get output stream to write from it
    OutputStream out = child.getOutputStream();

    out.write("<execute the java class by mentioning the usual command>");
    out.flush();

    out.close();
} catch (IOException e) {
}
试试看{
//执行命令
String command=“cmd/c start cmd.exe”;
Process child=Runtime.getRuntime().exec(命令);
//获取要从中写入的输出流
OutputStream out=child.getOutputStream();
请写出(“”);
out.flush();
out.close();
}捕获(IOE异常){
}

如果你想用这个程序编译不同的java文件,你可以试试这个方法

public class Laj {

  private static void printLines(String name, InputStream ins) throws Exception {
    String line = null;
    BufferedReader in = new BufferedReader(
        new InputStreamReader(ins));
    while ((line = in.readLine()) != null) {
        System.out.println(name + " " + line);
    }
  }

  private static void runProcess(String command) throws Exception {
    Process pro = Runtime.getRuntime().exec(command);
    printLines(command + " stdout:", pro.getInputStream());
    printLines(command + " stderr:", pro.getErrorStream());
    pro.waitFor();
    System.out.println(command + " exitValue() " + pro.exitValue());
  }

  public static void main(String[] args) {
    try {
      runProcess("javac YourDir/HelloWorld.java");
      runProcess("java YourDir.HelloWorld");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}


您可能想先编译其他源代码。Java编译器实际上是用Java本身编写的。您不需要调用javac.exe,而是查看
javax.tools.ToolProvider.getSystemJavaCompiler()

一旦用它编译了源代码文件,就可以使用类加载器加载编译器类文件并从那里调用代码,可能是通过反射的方式


总的来说,您需要一个高级用例。

您不能运行.java文件,它们不是可执行文件。您是否正在尝试运行已编译的内容?或者您也在尝试从Java内部运行编译器?您想运行可执行的.jar文件吗?也许您想打开texteditor?您可以创建批处理文件并从Java运行该批处理文件来动态编译和加载Java类,最好使用JavaCompiler。我不认为
javac
应该以大写字母
J
开头。这里有一个错误:java.io.IOException:无法运行程序“javac”:CreateProcess error=2,系统找不到指定的文件
public class HelloWorld {
  public static void main(String[] args) {
    System.out.println("ok");
  }
}