2

I want to make a java program that reads another java program from a file, compiles it and shows error and warnings.

Also I want to show the output of the program that was read from the file and compiled.

How can I do this?

1
  • +1 Interesting question. I'd like to see what answers come up. Commented Nov 25, 2010 at 12:43

4 Answers 4

3

Take a look at javax.tools.JavaCompiler.

Interface to invoke Java™ programming language compilers from programs.

The compiler might generate diagnostics during compilation (for example, error messages). If a diagnostic listener is provided, the diagnostics will be supplied to the listener. If no listener is provided, the diagnostics will be formatted in an unspecified format and written to the default output, which is System.err unless otherwise specified. Even if a diagnostic listener is supplied, some diagnostics might not fit in a Diagnostic and will be written to the default output.

Here's a little code-snippet I've used recently:

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

fileManager.setLocation(StandardLocation.CLASS_OUTPUT, compileDirList);


Iterable<? extends JavaFileObject> compilationUnits = 
       fileManager.getJavaFileObjectsFromFiles(files);

List<String> opts = new ArrayList<String>();
// set compiler's classpath to be same as the runtime's
opts.addAll(Arrays.asList("-classpath", System.getProperty("java.class.path")));

// do the actual compilation
compiler.getTask(null, fileManager, null, opts, null, compilationUnits).call();
Sign up to request clarification or add additional context in comments.

Comments

1

This has to be an assignment. Start here

Comments

0

Just use System.exec to execute javac. Then you can just pipe the output to a file which you read when it's done compiling. Something like this:

System.exec("javac *.java > output.out"); readFile("output.out");

Hope it helps.

Comments

0

A 'Java program that reads another Java program from a file, compiles it, and shows errors and warnings' is called a Java compiler. It's already written. All you have to do is invoke it, either via its API or exec().

1 Comment

how to implement it using exec()? while i'm trying is: Process p=Runtime.getRuntime().exec("javac FileName.java"); <consider that the file is already present there> but no o/p is produced.

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.