-3

I want to create a program that can Compile a .java file to a .class file like it is done on this website: Innovation website

My questions are:

  • Is there an library i can use to do this?
  • Where can I get this Library?
  • If there isn't a library for this then how can i do this?
3
  • It is compiling the files. You have to get the files and pass them as arguments to the jdk. I don't think there is a library to do this. This is very straight forward once you know how java works. Commented Jan 11, 2015 at 13:10
  • @luanjot It's there in JDK since 1.6. Commented Jan 11, 2015 at 13:19
  • possible duplicate of How to run Java program in command prompt Commented Jan 11, 2015 at 13:25

3 Answers 3

6
   JavaCompiler javac = ToolProvider.getSystemJavaCompiler();

The javadoc for JavaCompiler shows how to work and compile with this JDK facility. One snippet from there:

   File[] files1 = ... ; // input for first compilation task

   JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
   StandardJavaFileManager fileManager = compiler.getStandardFileManager(null, null, null);

   Iterable<? extends JavaFileObject> compilationUnits1 =
       fileManager.getJavaFileObjectsFromFiles(Arrays.asList(files1));
   compiler.getTask(null, fileManager, null, null, null, compilationUnits1).call();

It is by no means a simple task. But a general method for invoking a Java compiler via the shell - with all the trimmings - isn't easy either, and this, then, also applies to calls via Process.

Sign up to request clarification or add additional context in comments.

1 Comment

Question: how to provide the target location of the class file to be created? Is there created any file in thi ssolution???
2

You can do this using the Process class as

Process pro=Runtime.getRuntime().exec("javac FileName.java", null, new File("\path"));

5 Comments

The /path is the output file path right?
No its input file FileName.java path, output file will be generated at the same location
O right is there an way to move the files to another directory using the process?
Nvm I just had to add -d /outputPath to the process
Ya exactly! -d <directory> to generate it to specific directory
0

use ProcessBuilder to execute system commands.

Install JDK and form command "javac JavaFileName" pass this to ProcessBuilder constructor and call method start()

1 Comment

We have seen this often enough in the referenced duplicates.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.