2

I am looking at ways to compile java files and I know you can compile Java files from the command line using javac Test.java, but is there a way to pass this call to the command line?

Also is there a way to get the command line to compile .tar files in the same way... something like javac -tar Test.tar(passing command from java file).. or what would be the best way to do this?

Sorry im not very good at cmd commands

2

5 Answers 5

5

Java provides an interface to invoke the compilers from programs.

JavaCompiler compiler = ToolProvider
    .getSystemJavaCompiler();

StandardJavaFileManager fileManager = compiler
    .getStandardFileManager(null, null, null);

Iterable<? extends JavaFileObject> compilationUnits = fileManager
    .getJavaFileObjectsFromStrings(Arrays.asList("MyClass.java"));

compiler.getTask(null, fileManager, null, null, null, compilationUnits).call();

fileManager.close();
Sign up to request clarification or add additional context in comments.

2 Comments

I was actually looking at this way of compiling projects and it seems to be compiling but when you try to compile projects that have multiple classes it is not recognizing all the classes (ie. one class that is calling another), it is compiling all the classes but giving out about the import statements for the other classes and anywhere where a method from the other class is called... do you know why this would be happening?
You probably have to set the classpath option.
3
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("javac Test.java");

Comments

3

You can run system commands from Java using the Runtime class, e.g.

Process p = Runtime.getRuntime().exec("javac Test.java"); 
p.waitFor(); 

BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream())); 
String line; 
while((line = reader.readLine()) != null) { 
    System.out.println(line); 
} 

2 Comments

just playing around with it here, and just wondering can you put this in a method and call it when you want of does it have to be inside the main method? ...'public static void main(String[] args)
It can be in a method. public void execute(String command) throws Exception { ... } then you can call execute('java Test.java')
2

I believe you are asking how to pass a compile command to the command line from java file to compile another java file. This would be done like you would execute any other command to the command line. In my opinion I use process builder for everything, however, this is a great example of when to use .exec() and pass your command line compile command as a string.

Comments

2

Try this....

Process p = Runtime.getRuntime().exec("javac Test.java");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.