1

I wrote a simple program using compiler API and store a string which contains simple Java program into a file and compiles that file. Its working fine, now I need to print the output generated by the sample class. How can I do it?

String program="public class MyClass{ public static void main(String args[])    {System.out.println(\"My Method Called\");}}";
File newTextFile = new File("D:\\MyClass.java");

FileWriter fw = new FileWriter(newTextFile);
fw.write(program);
fw.close();
JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
FileOutputStream err = new FileOutputStream("Error.txt");
      FileOutputStream out = new FileOutputStream("output.txt");  

int results = compiler.run(null,err,out,"newtextfile");
if(results== 0){

        System.out.println("Compilation is successful");

    }else{
        System.out.println("Compilation Failed");
    }

}

It print only the result as Compilation is successful. How can I print the message in the sample class which is compiled.Please advice.

Now it creates output and error file but only errors are written in the error file if program has any error in it.If program compiles without any mistake then output is not written in the output file,empty file is created.

Mahes_sa_jey
  • 189
  • 3
  • 12
  • Here is an example: http://stackoverflow.com/q/14282726/829571 - you need to set the output `.class` file and load the new class with a ClassLoader. – assylias Dec 27 '13 at 14:41
  • this example looks pretty good : http://mike-java.blogspot.com/2008/03/java-6-compiler-api-tutorial.html – Ashish Dec 27 '13 at 14:50

3 Answers3

0
Process p = Runtime.getRuntime().exec("java my_class_file.class");
/* running compiled code in a separated process */
InputStream in = p.getInputStream();
InputStream err = p.getErrorStream();
OutputStream out = p.getOutputStream();
/* in,err and out streams */
0

Is that you need?

// Return compilation log!
public String compile(String compilationCommand){     
Process p = null;
try {
    p = Runtime.getRuntime().exec(compilationCommand);
    p.waitFor();
} catch (IOException e) {

} catch (InterruptedException e) {

}

Scanner scanner = new Scanner(p.getInputStream());
String result = null;

try{
    result = scanner.useDelimiter("$$").next();
} catch (NoSuchElementException e) {

}
scanner.close();

if(result != null)
   return "Compilation is successful";
else
  return "Compilation Failed\n" + result;
}
Mayke Ferreira
  • 174
  • 2
  • 9
0
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.*;
import javax.tools.*;
import javax.annotation.processing.*;
import javax.lang.model.*;
import javax.lang.model.element.*;
import javax.lang.model.type.*;
import javax.lang.model.util.*;
import java.net.URI;

public class Compile2 extends JPanel implements ActionListener
{
static private final String newline = "\n";
JButton compileButton;
JTextArea log;
JFileChooser fc;

public Compile2()
{
    super(new BorderLayout());

    log = new JTextArea(5, 20);
    log.setMargin(new Insets(5, 5, 5, 5));
    log.setEditable(false);
    JScrollPane logScrollPane = new JScrollPane(log);

    fc = new JFileChooser();

    compileButton = new JButton("Compile");
    compileButton.addActionListener(this);          

    JPanel buttonPanel = new JPanel();
    buttonPanel.add(compileButton);
  

    add(buttonPanel, BorderLayout.PAGE_START);
    add(logScrollPane, BorderLayout.CENTER);
}

public void actionPerformed(ActionEvent e)
{
    if(e.getSource() == compileButton)
    {
        int returnVal = fc.showOpenDialog(Compile2.this);
        if(returnVal == JFileChooser.APPROVE_OPTION)
        {
            File file = fc.getSelectedFile();
            log.append("Compiling file: " +file.getName()+ "." +newline);
            JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager fileManager = 
javac.getStandardFileManager(null, null, null);
            Iterable<? extends JavaFileObject> compilationUnits1 = 
fileManager.getJavaFileObjects(file);
            javac.getTask(null, fileManager, null, null, null, 
compilationUnits1).call();

            DiagnosticCollector<JavaFileObject> diagnostics = new 
DiagnosticCollector<JavaFileObject>();
            StandardJavaFileManager fileManager2 = 
javac.getStandardFileManager(diagnostics, null, null);
            javac.getTask(null, fileManager, diagnostics, null, null, 
compilationUnits1).call();
            for(Diagnostic<? extends JavaFileObject> diagnostic: 
diagnostics.getDiagnostics())
                System.out.format("Error on line %d in %s%n", 
diagnostic.getLineNumber(), diagnostic.getSource().toUri());
                
            class JavaSourceFromString extends SimpleJavaFileObject
            {
                final String code;
                public JavaSourceFromString(String name, String code) 
                {
                    super(URI.create("string:///" + name.replace('.','/') + 
Kind.SOURCE.extension),
                        Kind.SOURCE);
                    this.code = code;
                }

                @Override
                public CharSequence getCharContent(boolean 
ignoreEncodingErrors) {
                    return code;
                }
            }
            
            log.append("Class file created!" +newline);
        } 
        log.setCaretPosition(log.getDocument().getLength());
    }

}

private static void Show()
{
    JFrame frame = new JFrame("Compiler");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.add(new Compile2());
    
    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        public void run()
        {
            UIManager.put("swing.boldMetal", Boolean.FALSE);
            Show();
        }
    }
    );
}
}
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 15 '21 at 07:22