简体   繁体   English

编译器可编译其他Java文件

[英]Compiler to compile other java files

I am trying to compile and run java files from java code. 我正在尝试从Java代码编译和运行Java文件。 I have a compiled java class and with this, try to compile java code. 我有一个编译的Java类,并尝试编译Java代码。 below is my code, but I don't see *.class file in either bin (in eclipse project out put folder) or in source place. 下面是我的代码,但是在bin(在Eclipse项目的put文件夹中)或源代码中都看不到* .class文件。 Where has gone my *.class file if my compiler success. 如果我的编译器成功,我的* .class文件在哪里。 Or what is the wrong with my code? 还是我的代码有什么问题? Trying in below 2 ways: 请尝试以下2种方法:

public class CompilerClass {  

    public static void main(String[] args) throws Exception {  

             Process p = Runtime.getRuntime().exec("javac com.java.Compileable.java");
             ProcessBuilder pb = new ProcessBuilder("javac", "com.java.Compileable.java");
    }  
}  

well as an alternative you can use java compiler API 以及您可以使用Java编译器API的替代方法

package javacompiler;
import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
public class COmpilerHello {
    public static void main(String[] args)
    {
        String s="C:/Users/MariaHussain/Desktop/hussi.java";
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int result = compiler.run(System.in,System.out,System.err,s);
        System.out.println("Compile result code = " + result);
    }
}

Test it with file you have in the same directory as your CompilerClass 使用与CompilerClass位于同一目录中的文件进行测试

public static void main(String[] args) throws Exception {  

         Process p = Runtime.getRuntime().exec("javac SomeClass.java");
         ProcessBuilder pb = new ProcessBuilder("javac", "SomeClass.java");
}  

Works fine for me. 对我来说很好。 SomeClass.java being in same directory as CompilerClass SomeClass.javaCompilerClass位于同一目录

Ran from command line 从命令行运行

you have to state the location of the file. 您必须说明文件的位置。 It should be something like this 应该是这样的

public static void main(String[] args) throws Exception {  

         Process p = Runtime.getRuntime().exec("javac C://JavaProject//SomeClass.java");
         ProcessBuilder pb = new ProcessBuilder("javac", "C://JavaProject//SomeClass.java");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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