1

I have a simple code to make Java code compiler

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.tools.*;
import java.io.*;
import java.util.*;

public class Compiler extends JFrame
{
    String loc="D:\\java";
    File file=null,
         dir=null;
    boolean success;
    public Compiler()
    {
        super("Highlight example");
        try 
        {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } 
        catch (Exception evt) {}
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new GridLayout(1,2));

        JTextPane textPane = new JTextPane();
        JTextArea debug=new JTextArea();
        JButton comp=new JButton("Compile"),
                browse=new JButton("...");

        JTextArea location=new JTextArea();

        JPanel right=new JPanel(),
               up=new JPanel();

        up.setLayout(new BorderLayout());
        up.add(new JScrollPane(location),"Center");
        up.add(browse,"East");

        right.setLayout(new BorderLayout(2,1));
        right.add(up,BorderLayout.NORTH);
        right.add(new JScrollPane(textPane), "Center");
        right.add(comp,"South");
        add(right);
        add(new JScrollPane(debug));
        setSize(800, 400);
        setVisible(true);

        browse.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                success=false;
                UIManager.put("FileChooser.readOnly", Boolean.TRUE);
                JFileChooser fc = new JFileChooser(loc);
                int status = fc.showOpenDialog(new JFrame());
                if (status==JFileChooser.APPROVE_OPTION)
                {
                    debug.setText("");
                    file = fc.getSelectedFile();
                    dir = fc.getCurrentDirectory();
                    try
                    {
                        textPane.read(new FileReader(file), null);
                    }
                    catch(Exception ex)
                    {

                    }
                }
            }
        });

        comp.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                    {   
                        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
                        DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
                        StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null, null);
                        Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjectsFromStrings(Arrays.asList(file+""));
                        String[] option=new String[]{"-g","-parameters"};
                        Iterable<String> options = Arrays.asList(option);
                        JavaCompiler.CompilationTask task=null;

                        fileManager.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(dir));

                        task = compiler.getTask(null, fileManager, diagnostics, options, null, compilationUnits);
                        success = task.call();

                        fileManager.close();
                 //     System.out.println("Success: " + success);
                        if(success==true)
                        {
                            debug.setText("Success");
                        }
                        else
                        {
                            int i=1;
                            for (Diagnostic diagnostic : diagnostics.getDiagnostics())
                                if(diagnostic.getLineNumber()!=-1)
                                    debug.append("Error on line "+diagnostic.getLineNumber()+" in "+ diagnostic+"\n");
                        }
                    }
                    catch(Exception ex)
                    {

                    }
            }
        });
    }

    public static void main(String[]args)
    {
        new Compiler();
    }
}

I don't know why compiler can not find previous result of code before. And I have no idea how to fix that.

For more details, I made an example :

  1. select A.java select A.java

  2. Content of A.java result A

  3. then I have select B.java. look A.java has been compiled with create A.class enter image description here

  4. B.java can not compile because it can not find class A enter image description here

And also can not find class inside package folder.

Here is example 2:

enter image description here

A.java has been compiled with create folder <path>\a\b

enter image description here

and access class using import

enter image description here

I have some try

from :

fileManager.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(dir));

to :

fileManager.setLocation(javax.tools.StandardLocation.CLASS_PATH, Arrays.asList(dir));

but it's not working

2
  • It's a bit hard to tell from your pictures where those files live. Do they both live in this example folder or do they live in some folder structure a/b? Commented Jul 17, 2016 at 23:17
  • @Makoto java file inside example folder, class file inside structure a/b folder if they are contains package. Commented Jul 17, 2016 at 23:30

3 Answers 3

1

In addition to setting javax.tools.StandardLocation.CLASS_OUTPUT, you need to set javax.tools.StandardLocation.CLASS_PATH to include the same location where you put the previous output:

fileManager.setLocation(javax.tools.StandardLocation.CLASS_OUTPUT, Arrays.asList(dir));
// Set dirClassPath to include dir, and optionally other locations
fileManager.setLocation(javax.tools.StandardLocation.CLASS_PATH, Arrays.asList(dirClassPath));
Sign up to request clarification or add additional context in comments.

4 Comments

i think it doesn't work if A.java using package, and B using import, post updated.
@newbie You are not importing it correctly. It should be import a.b.*;
@newbie It does not look like the compiler sees that change (the error message still shows no asterisk after b).
@newbie That's odd. I assume that a/b/ directory contains A.class, right?
1

You need to specify the sourcepath directory, your code

String[] option=new String[]{"-g","-parameters"};,

try this

String[] option=new String[]{"-g","-sourcepath", loc};

where loc is the root directory for the B class. With A properly stored inside its own package.

I've tried your code, with my modification http://kurungkurawal.com/gifs/tut-compile.gif

Comments

0

Create jar File of external classes and attach with compiler.

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

JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics, optionList, null,
                compilationUnit);

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.