Hi,

Is it possible to create a Java compiler? Could you make a Notepad-like application, save the code as a .java file, compile it into a .class file, and run it? Basically, I want to combine Notepad and Command Prompt. I just need help on the compiling part (and listing the errors, if any).

Thanks in advanced for your help.

hi,
I had once made a full fledge editor for java in java. All i did was to include the classpath while issuing the javac command.

I used
Process process=Runtime.getRuntime().exec("javac -cp <java file>");
then I used err stream and output stream to read the output.
The same i used for java command as well.

regards
srinivas

To run a class you don't need to launch the java executable.
Create a classloader and use that to fork off the class in-process :)

You can also do that to compile classes. Simply hook into Ant which is a Java application and can compile Java classes for you (by hooking into the JDK).
Examining the Ant source should be interesting (I've not yet done so) to see how they do it in a platform independent way.

thanks guys!

jwenting - WHOA!!!!!!!! You're approach is really confusing! I think I'll stick with the other method but thanks for your reply.

cheenu78 - thanks! can u explain how to get the error messages a little more. Thanks again.

confusing? It's what I'd do. It's platform independent which is important as I work on several operating systems at the same time (Windows, 2 versions of Linux, and AIX, and I hope to add a Mac sometime next year).
And calling Ant should be rather easy. probably easier in fact than capturing the commandline output.

would you mind explaining how to use Ant then??

Thank you very much for your help.

Ant is a tool similar to make (which is for C/C++ mainly).
It's written completely in Java so can easily integrate with Java applications.

There's books written about it, I'm barely scratching the surface by using it from the commandline to compile and package my projects.
Maybe next year when I may have time to do more I'm going to really dive into it :)

http://ant.apache.org

Hi!

I started to make the compiler but I have some problems. First, it won't compile. Second, I can't get the error messages/output to appear. My code is below. Thanks in advanced for your help.

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

public class JEdit extends JFrame implements ActionListener
{

  JButton open = new JButton("Open");
  JButton save = new JButton("Save");
  JButton compile = new JButton("Compile");
  JButton run = new JButton("Run");
  JButton help = new JButton("Help");

  JTextArea code = new JTextArea("",28,65);
  JTextArea output = new JTextArea("",7,65);

  File fileS = null;

  Font cf = new Font("monospaced",Font.PLAIN,12);

  public JEdit()
  {
    super("Java CinnaComp");
    setSize(500,710);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);

    Container contentArea = getContentPane();
    contentArea.setBackground(Color.lightGray);

    FlowLayout flowManager = new FlowLayout();
    contentArea.setLayout(flowManager);

    contentArea.add(save);
    save.addActionListener(this);
    contentArea.add(open);
    open.addActionListener(this);
    contentArea.add(compile);
    compile.addActionListener(this);
    contentArea.add(run);
    run.addActionListener(this);
    contentArea.add(help);
    help.addActionListener(this);
    JScrollPane scrollPane = new JScrollPane(code,
                                             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    contentArea.add(scrollPane);
    code.setFont(cf);
    JScrollPane scrollPane2 = new JScrollPane(output,
                                             JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
                                             JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
    contentArea.add(scrollPane2);
    output.setFont(cf);


    setContentPane(contentArea);
  }

  public void actionPerformed(ActionEvent event)
  {
    if(event.getSource() == save)
    {
      JFileChooser saveChooser = new JFileChooser();
      saveChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      int result = saveChooser.showSaveDialog(this);
      if(result == JFileChooser.CANCEL_OPTION)
        return;
      fileS = saveChooser.getSelectedFile();
      if(fileS == null || fileS.getName().equals(""))
        JOptionPane.showMessageDialog(null, "Invalid File Name",
                    "Invalid File Name", JOptionPane.ERROR_MESSAGE);
      else
      {
        try
        {
          FileWriter saveFile = new FileWriter(fileS.getPath());
          BufferedWriter bufferS = new BufferedWriter(saveFile);
          bufferS.write(code.getText());
          bufferS.close();
        }
        catch (Exception e1)
        {
        }
      }
    }

    if(event.getSource() == open)
    {
      JFileChooser openChooser = new JFileChooser();
      openChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
      int result2 = openChooser.showOpenDialog(this);
      if(result2 == JFileChooser.CANCEL_OPTION)
        return;
      File fileO = openChooser.getSelectedFile();
      if(fileO == null || fileO.getName().equals(""))
        JOptionPane.showMessageDialog(null, "Invalid File Name",
                    "Invalid File Name", JOptionPane.ERROR_MESSAGE);
      else
      {
        try
        {
          FileReader openFile = new FileReader(fileO.getPath());
          BufferedReader bufferO = new BufferedReader(openFile);
          String textline = null;
          while((textline = bufferO.readLine()) != null)
          {
            code.append(textline+"\n");
          }
          bufferO.close();
        }
        catch (Exception e2)
        {
        }
      }
    }

    if(event.getSource()==compile)
    {
      try
      {
        Process compile = Runtime.getRuntime().exec("javac -cp " +
            fileS.getPath());
        output.setText(compile.getErrorStream().toString());
      }
      catch(Exception e3)
      {
        output.append("\n"+e3.toString());
      }
    }

    if (event.getSource() == run) {
      try {
        Process run = Runtime.getRuntime().exec("java -cp " +
            fileS.getParent()+fileS.getName());
        output.setText(run.getErrorStream().toString());
        output.append("\n"+run.getOutputStream().toString());
      }
      catch (Exception e4) {
        output.append("\n" + e4.toString());
      }
    }

  }


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

The trick is building the xml file to have ant do tricks like run unit tests, deploy your application to a J2EE server, and things like that :)

And of course integrating Ant inside another application is a bit more involved than just calling the command from the prompt.

Hi everyone,

jwenting is right. Plug in ant as its more useful and easier and to build an ide is not an easy task. But if you want to still pursue it read up about pipe streams in java. You will also have to use window listeners and not set a default closing for the JFrame.

Richard West

Of course what he's doing/planning isn't really to make a compiler but to call an external compiler :)

true, but can you help me with what i have so far?

thanx.

Dear Ghost,

I want to make a Java Compiler in Java.

Is it possible to create a Java compiler? Could you

make a Notepad-like application, save the code as

a .java file, compile it into a .class file, and run it?

Basically, I want to combine Notepad and Command

Prompt. I think u have that Code. Please send that

full coding please. Im waiting for ur seen reply.

Thanks in advanced for your help

Hi everyone,

Is it possible to create a Java compiler? Could you
make a Notepad-like application, save the code as
a .java file, compile it into a .class file, and run it?

It seems you want to create an ide and not a comppiler but the answer is that its possible

Basically, I want to combine Notepad and Command Prompt.

Duly noted

I think u have that Code. Please send that full coding please

I doubt he or anyone including myself will send the code.
What you can do is create a topic on creatig an ide by yourself and i'm sure the others will walk you through it if you have specific questions

Here are some tips for you
Runtime
JTextArea
Pipe And Streams

Richard West

I'll help you with your program, but you need to show some effort! At least create the GUI and TRY to send commands to command prompt. Then I'll be glad to help.

Can you help me wlth the following work?:
This sample program shows how to print the current month, now using the "Calendar" object (instead of the Date object which has been deprecated, meaning it has been slated for removal from the language).

// Program prints the current month

import java.util.Calendar;

public class ShowToday {
static String[] monthArray = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };

public static void main(String[] args) {
Calendar rightNow = Calendar.getInstance();
int month = rightNow.get( Calendar.MONTH );
// This will be a number from 0 to 11, representing January to December
System.out.println("month: " + month );
// Using the above array, this will print "Jan" thru "Dec"
System.out.println("month: " + monthArray[month] );
}
}

good day to all.
i stumble upon this site because i want to know how to make an interpreter for our project.
we are using jflex as our lexical analyzer.
may i know what's the next step in doing?
thanks

Hi, I worked on the problem and could able to crack it
please find the code below

package JCompiler;

import java.awt.EventQueue;

public class JCompiler {

    private JFrame frame;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    JCompiler window = new JCompiler();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the application.
     */
    public JCompiler() {
        initialize();
    }

    /**
     * Initialize the contents of the frame.
     */
    private void initialize() {
        frame = new JFrame();
        frame.setResizable(false);
        frame.setBounds(100, 100, 894, 567);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setLayout(null);

        final TextArea taEditor = new TextArea();
        taEditor.setBounds(10, 47, 868, 376);
        frame.getContentPane().add(taEditor);

        final TextArea taResult = new TextArea();
        taResult.setEditable(false);
        taResult.setBounds(9, 429, 869, 100);
        frame.getContentPane().add(taResult);

        final JLabel lblStatus = new JLabel("");
        lblStatus.setBounds(518, 11, 360, 30);
        frame.getContentPane().add(lblStatus);

        JButton btnNew = new JButton("NEW");
        btnNew.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                lblStatus.setText("");
                taEditor.setText("");

            }
        });
        btnNew.setBounds(10, 11, 89, 23);
        frame.getContentPane().add(btnNew);

        JButton btnOpen = new JButton("OPEN");
        btnOpen.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser chooser = new JFileChooser();
                FileNameExtensionFilter filter = new FileNameExtensionFilter(
                    "Java Files", "java");
                chooser.setFileFilter(filter);
                int returnVal = chooser.showOpenDialog(null);
                if(returnVal == JFileChooser.APPROVE_OPTION) {

                    System.out.println("You chose to open this file: " +chooser.getSelectedFile().getName());
                   lblStatus.setText(chooser.getSelectedFile().getAbsolutePath());
                   String ch = "";
                   taEditor.setText(ch);
                   try {
                       BufferedReader br = new BufferedReader(new InputStreamReader( new FileInputStream(chooser.getSelectedFile().getAbsolutePath())));

                    while((ch = br.readLine()) != null)
                        taEditor.append(ch+"\n");

                    br.close();

                } catch (FileNotFoundException fe)
                {

                }
                   catch(IOException e)
                   {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

                }
            }
        });
        btnOpen.setBounds(109, 11, 89, 23);
        frame.getContentPane().add(btnOpen);

        JButton btnSave = new JButton("SAVE");
        btnSave.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                JFileChooser saveChooser = new JFileChooser();
                int chooserVal = saveChooser.showSaveDialog(null);
                if(chooserVal == JFileChooser.APPROVE_OPTION)
                {
                    try
                    {
                        PrintWriter pw = new PrintWriter(saveChooser.getSelectedFile());
                        pw.print(taEditor.getText());
                        pw.close();
                    }
                    catch(FileNotFoundException fe){
                        //Logger.getLogger(arg0)
                    }
                }
            }
        });
        btnSave.setBounds(208, 11, 89, 23);
        frame.getContentPane().add(btnSave);

        JButton btnCompile = new JButton("COMPILE");
        btnCompile.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String file = lblStatus.getText();
                String fname="";
                String dir ="";
                System.out.println("---->"+file);
                System.out.println(file.substring(file.length()-4, file.length()));

                for(int i=file.length()-1;i>0;i--)
                {
                    if(file.charAt(i)=='\\')
                      { 
                          System.out.println("dir == "+file.substring(0,i));
                          System.out.println("file == "+file.substring(i+1,file.length()));
                          dir = file.substring(0,i);
                          fname = file.substring(i+1,file.length());
                          break;
                      }
                }
                System.out.println("----javac "+fname+"  file "+fname.substring(fname.length()-4, fname.length()));
                if(fname.substring(fname.length()-4, fname.length()).equals("java"))
                {
                    try
                      {

                        Process compile = Runtime.getRuntime().exec("javac "+fname,null,new File(dir));
                        System.out.println("--->"+compile.getInputStream());

                        BufferedReader br = new BufferedReader(new InputStreamReader(compile.getInputStream()));

                        String ch = new String();
                        while((ch=br.readLine())!=null)
                            taResult.append(ch);
                      }
                      catch(Exception e3)
                      {
                          taResult.append("\nERROR->"+e3.toString());
                      }

                }
                else
                {
                    taResult.setText("INVALID FILE");
                }
            }
        });
        btnCompile.setBounds(307, 11, 89, 23);
        frame.getContentPane().add(btnCompile);


        JButton btnExecute = new JButton("EXECUTE");
        btnExecute.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                String file = lblStatus.getText();
                String fname="";
                String dir ="";
                System.out.println("---->"+file);
                System.out.println(file.substring(file.length()-4, file.length()));

                for(int i=file.length()-1;i>0;i--)
                {
                    if(file.charAt(i)=='\\')
                      { 
                          System.out.println("dir == "+file.substring(0,i));
                          System.out.println("file == "+file.substring(i+1,file.length()-5));
                          dir = file.substring(0,i);
                          fname = file.substring(i+1,file.length()-5);
                          break;
                      }
                }
                System.out.println("----java "+fname+"  file "+fname.substring(fname.length()-4, fname.length()));

                    try
                      {

                        Process run = Runtime.getRuntime().exec("java "+fname,null,new File(dir));
                        System.out.println("--->"+run.getInputStream());

                        BufferedReader br = new BufferedReader(new InputStreamReader(run.getInputStream()));

                        String ch = new String();
                        while((ch=br.readLine())!=null)
                            taResult.append(ch+"\n");
                      }
                      catch(Exception e3)
                      {
                          taResult.append("\nERROR->"+e3.toString());
                      }

            }
        });
        btnExecute.setBounds(406, 11, 89, 23);
        frame.getContentPane().add(btnExecute);

    }
}

not sure what to think of it, after all, it's a reply to a dead thread.
but some advice: I would be careful with code like this:

catch (FileNotFoundException fe)
                {
                }

this is just hours of needles debugging waiting to happen.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.