在运行时运行编译的java代码

我想运行之前编译的代码.我编译无论如何编译并不重要,但运行代码是问题.

我的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指定类路径

实际上没有错误nope.但是你没有捕获它们.捕获错误你可以使用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();
        }
    }
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...