Chowdappa
Chowdappa

Reputation: 1620

Compiler to compile other java files

I am trying to compile and run java files from java code. I have a compiled java class and with this, try to compile java code. below is my code, but I don't see *.class file in either bin (in eclipse project out put folder) or in source place. Where has gone my *.class file if my compiler success. Or what is the wrong with my code? Trying in below 2 ways:

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");
    }  
}  

Upvotes: 1

Views: 151

Answers (3)

Jeremy
Jeremy

Reputation: 641

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");
}

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 208944

Test it with file you have in the same directory as your 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

Ran from command line

Upvotes: 0

well as an alternative you can use java compiler 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);
    }
}

Upvotes: 2

Related Questions