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?

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
Sanket
  • 149
  • 1
  • 8

4 Answers4

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();
Community
  • 1
  • 1
Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
1

This has to be an assignment. Start here

The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
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.

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().

user207421
  • 305,947
  • 44
  • 307
  • 483
  • how to implement it using exec()? while i'm trying is: `Process p=Runtime.getRuntime().exec("javac FileName.java");` but no o/p is produced. – Mohammad Faisal Sep 13 '11 at 15:35