运行 在运行时编译 java 代码

Running compiled java code at runtime

我想运行之前编译过的代码。无论如何我编译了如何编译并不重要但是运行宁代码是问题。

我的code.java

public class code{

    public static void main(String[] args) {
        System.out.println("Hello, World");
    }
}

然后我编译了这段代码,生成了code.class(在D://目录下)。现在我要运行这个编译后的文件。我的代码是:

import java.io.IOException;
import java.io.InputStream;

public class compiler {
   public static void main(String[] args) {
      final String dosCommand = "cmd /c java code";
      final String location = "D:\";
      try {
         final Process process = Runtime.getRuntime().exec(
            dosCommand + " " + location);
         final InputStream in = process.getInputStream();
         int ch;
         while((ch = in.read()) != -1) {
            System.out.print((char)ch);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
   }
}

这里没有错误,但是这段代码没有做任何事情。没有打开cmd,什么都没有。我哪里错了?我该怎么办?

当前你的cmd命令是错误的。

cmd /c java code D:/   /*this is not correct cmd command*/

应该是

cmd /c java -cp D:/ code

当您 运行 一个 .class 文件在不同的文件夹中但不在当前文件夹中时,使用 -cp 指定 class 路径

there is no error 不,实际上有。但你没有捕获它们。要捕获错误,你可以使用 getErrorStream()

示例代码

public class compiler {

    public static void main(String[] args) {
        final String dosCommand = "cmd /c java -cp ";
        final String classname = "code";
        final String location = "D:\";
        try {
            final Process process = Runtime.getRuntime().exec(dosCommand + location + " " + classname);
            final InputStream in = process.getInputStream();
            final InputStream in2 = process.getErrorStream();
            int ch, ch2;
            while ((ch = in.read()) != -1) {
                System.out.print((char) ch);
            }
            while ((ch2 = in2.read()) != -1) {
                System.out.print((char) ch2); // read error here
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}