1 2 Previous Next 23 Replies Latest reply: Dec 29, 2003 6:23 PM by 807582 RSS

    Running Java Inside My IDE

    807582
      This is not easy as you think it is. I'm creating my Java IDE and I'm already finish w/ the compiling and reading of error process. This Java IDE is just basically writing your codes and compile it and run it inside the IDE, the main problem is the run portion does not work, how do I solved this.

      Here is the snippet of the codes :

      Lets assume that Sample is finish compiling.
      In here I was trying to execute 1 class which is named Sample.

      // This was the 1st
      Runtime r = Runtime.getRuntime();
      Process p = r.exec("c:/javac/bin/java -classpath c:\\Michael Sample");

      or this :

      //This was the second
      String java = "c:/javac/bin/java.exe";
      String file = "c:/Michael/Sample.class";

      Runtime r = Runtime.getRuntime();
      Process p = r.exec(java+" "+file);

      I tried all of this but does not work. How do I solved this,
      Any help is appriciated, Thanks.

      http://www.experts-exchange.com/Programming/Programming_Languages/Java/M_898315.html

      Javatm
        • 1. Re: Running Java Inside My IDE
          807582
          Hi,

          The following code works for me.
          import java.util.*;
          import java.io.*;
          
          
          public class Test
          {
          public static void main (String [] args) 
          throws IOException, InterruptedException 
          {
          Runtime r = Runtime.getRuntime();
          Process p = r.exec("cmd /c C:\\j2sdk1.4.2\\bin\\java.exe " + "-classpath .;c:\\new myprinter" );
          
          InputStreamReader in = new InputStreamReader( p.getErrorStream() );
          BufferedReader br = new BufferedReader( in );
          String inputLine;
          Vector vLines = new Vector();
          while ( (inputLine = br.readLine() ) != null) 
          {
          vLines.addElement(inputLine);
          }
          
          
          if ( ( p.waitFor() == 0 ) )
          {
          System.out.println( "Terminated normally." );
          }
          else
          {
          System.out.println( "Terminated abnormally." );
          for (int i=0; i < vLines.size(); ++i) 
          {
          System.out.println((String) vLines.elementAt(i)); 
          }
          }
          }
          }
          -Amol
          • 2. Re: Running Java Inside My IDE
            807582
            Process p = r.exec("cmd /c C:\\j2sdk1.4.2\\bin\\java.exe " + "-classpath .;c:\\new myprinter" );

            Lets say that I have a folder named Michael w/ a one class named Sample.class
            Can you check if this is correct :

            // Where javac is the folder of my jdk
            Process p = r.exec("cmd /c C:\\javac\\bin\\java.exe " + "-classpath .;c:\\Michael\\new Sample" );

            One more thing is this gonna open up a dos promt or not ?
            Thank you very much !.

            Javatm

            • 3. Re: Running Java Inside My IDE
              807582
              Hi ,

              If you Sample.class file is in directory "C:\\Michael" use
              Process p = r.exec("cmd /c C:\\javac\\bin\\java.exe " + "-classpath .;c:\\Michael\\ Sample" );

              else if it is in "C:\\Michael\\new " directory then use
              Process p = r.exec("cmd /c C:\\javac\\bin\\java.exe " + "-classpath .;c:\\Michael\\new Sample" );

              No , its not going to open a dos prompt.

              Get back if you have any other requirements.

              -Amol




              • 4. Re: Running Java Inside My IDE
                807582
                Okey I'll try what you just suggested pls. dont forget this question cause I'm
                gonna give updates on the result of the program.

                Thank you :)
                Javatm
                • 5. Re: Running Java Inside My IDE
                  807582
                  Hi,

                  If it works, don't forget to give the duke dollars :)

                  -Amol
                  • 6. Re: Running Java Inside My IDE
                    807582
                    And how about loading the compiled class dynamically and calling its main method?

                    This would be platform independent, but maybe this has some weaknesses that I don't know about...

                    Filip
                    • 7. Re: Running Java Inside My IDE
                      807582
                      If it works, don't forget to give the duke dollars :)
                      Sure I'm gonna try iy tommorow and I'll give the points
                      if it works thanks.


                      To FRj;
                      how about loading the compiled class dynamically and calling its main method?
                      What do you mean ? how do you do it ?
                      • 8. Re: Running Java Inside My IDE
                        807582
                        Well, I just have the very simple sample code that I found somewhere so I just post it here. There are just 2 classes that make a mini-IDE capable of creating the class, compiling it and running.
                        The usage is as follows: in the Class name field you enter the name of the class that you CREATE (without the '.java'), for ex. 'Test'. In the TextArea below you enter the body of the java file for that class, for ex.:
                        public class Test {
                            public static void main(String[] args)
                            {
                                System.out.println("Hello world");
                            }
                        }
                        It is important to not enter the name of the existing java file, as it will be overwritten.

                        And here is the code that does it:
                        RunItReload.java
                        import java.awt.*;
                        import java.awt.event.*;
                        import javax.swing.*;
                        import java.io.*;
                        import java.net.*;
                        import java.lang.reflect.*;
                        
                        public class RunItReload
                             extends JFrame {
                             
                             JPanel contentPane;
                             JScrollPane jScrollPane1     = new JScrollPane();
                             JTextArea source               = new JTextArea();
                             JPanel jPanel1                    = new JPanel();
                             JLabel classNameLabel          = new JLabel("Class Name");
                             GridLayout gridLayout1          = new GridLayout(2,1);
                             JTextField className          = new JTextField();
                             JButton compile                    = new JButton("Go");
                             Font boldFont                    = new java.awt.Font("SansSerif", 1, 11);
                        
                             public RunItReload()
                             {
                                  super("Editor");
                                  setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                                  contentPane = (JPanel) this.getContentPane();
                                  this.setSize(400, 300);
                                  classNameLabel.setFont(boldFont);
                                  jPanel1.setLayout(gridLayout1);
                                  compile.setFont(boldFont);
                                  compile.setForeground(Color.black);
                                  compile.addActionListener(new ActionListener() {
                                       public void actionPerformed(ActionEvent e)
                                       {
                                            try {
                                                 doCompile();
                                            } catch (Exception ex) {
                                                 System.err.println("Error during save/compile: " + ex);
                                            }
                                            System.gc();
                                       }
                                  });
                                  contentPane.add(jScrollPane1, BorderLayout.CENTER);
                                  contentPane.add(jPanel1, BorderLayout.NORTH);
                                  jPanel1.add(classNameLabel);
                                  jPanel1.add(className);
                                  jScrollPane1.getViewport().add(source);
                                  contentPane.add(compile, BorderLayout.SOUTH);
                             }
                             
                             public static void main(String[] args)
                             {
                                  Frame frame = new RunItReload();
                                  // Center screen
                                  Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                                  Dimension frameSize = frame.getSize();
                                  if (frameSize.height > screenSize.height) {
                                       frameSize.height = screenSize.height;
                                  }
                                  if (frameSize.width > screenSize.width) {
                                       frameSize.width = screenSize.width;
                                  }
                                  frame.setLocation((screenSize.width - frameSize.width) / 2, (screenSize.height - frameSize.height) / 2);
                                  frame.show();
                             }
                             
                             private void doCompile() throws Exception
                             {
                                  // write source to file
                                  String sourceFile = className.getText() + ".java";
                                  FileWriter fw = new FileWriter(sourceFile);
                                  fw.write(source.getText());
                                  fw.close();
                                  // compile it
                                  int compileReturnCode = com.sun.tools.javac.Main.compile(new String[] {sourceFile});
                                  if (compileReturnCode == 0) {
                                       // Create new class loader 
                                       // with current dir as CLASSPATH
                                       ClassLoader loader = new SimpleClassLoader();
                                       // load class through new loader
                                       Class aClass = loader.loadClass(className.getText());
                                       // run it
                                       Object objectParameters[] = {new String[]{}};
                                       Class classParameters[] = {objectParameters[0].getClass()};
                                       Method theMethod = aClass.getDeclaredMethod("main", classParameters);
                                       // Static method, no instance needed
                                       theMethod.invoke(null, objectParameters);
                                  }
                             }
                        }
                        SimpleClassLoader.java (with my modifications)
                        /*
                         * SimpleClassLoader.java - a bare bones class loader.
                         *
                         * Copyright (c) 1996 Chuck McManis, All Rights Reserved.
                         *
                         * Permission to use, copy, modify, and distribute this software
                         * and its documentation for NON-COMMERCIAL purposes and without
                         * fee is hereby granted provided that this copyright notice
                         * appears in all copies.
                         *
                         * CHUCK MCMANIS MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE
                         * SUITABILITY OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING
                         * BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY,
                         * FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT. CHUCK MCMANIS
                         * SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT
                         * OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
                         */
                        
                        import java.util.Hashtable;
                        //import util.ClassFile;
                        import java.io.ByteArrayInputStream;
                        import java.io.FileInputStream;
                        import java.io.*;
                        
                        public class SimpleClassLoader extends ClassLoader {
                            private Hashtable classes = new Hashtable();
                        
                            public SimpleClassLoader() {
                            }
                        
                            /**
                             * This sample function for reading class implementations reads
                             * them from the local file system
                             */
                            private byte getClassImplFromDataBase(String className)[] {
                        //         System.out.println("        >>>>>> Fetching the implementation of "+className);
                                 byte result[];
                                 try {
                                     FileInputStream fi = new FileInputStream(className+".class");
                                     result = new byte[fi.available()];
                                     fi.read(result);
                                     return result;
                                 } catch (Exception e) {
                        
                                     /*
                                      * If we caught an exception, either the class wasnt found or it
                                      * was unreadable by our process.
                                      */
                                     return null;
                                 }
                            }
                        
                            /**
                             * This is a simple version for external clients since they
                             * will always want the class resolved before it is returned
                             * to them.
                             */
                            public Class loadClass(String className) throws ClassNotFoundException {
                                return (loadClass(className, true));
                            }
                        
                            /**
                             * This is the required version of loadClass which is called
                             * both from loadClass above and from the internal function
                             * FindClassFromClass.
                             */
                            public synchronized Class loadClass(String className, boolean resolveIt)
                                 throws ClassNotFoundException
                             {
                                Class result;
                                byte  classData[];
                        
                        //        System.out.println("        >>>>>> Load class : "+className);
                        
                                /* Check our local cache of classes */
                        //        result = (Class)classes.get(className);
                        //        if (result != null) {
                        //            System.out.println("        >>>>>> returning cached result.");
                        //            return result;
                        //        }
                        
                                /* Check with the primordial class loader */
                                try {
                                    result = super.findSystemClass(className);
                        //            System.out.println("        >>>>>> returning system class (in CLASSPATH).");
                                    return result;
                                } catch (ClassNotFoundException e) {
                        //            System.out.println("        >>>>>> Not a system class.");
                                }
                        
                                /* Try to load it from our repository */
                                classData = getClassImplFromDataBase(className);
                                if (classData == null) {
                                    throw new ClassNotFoundException();
                                }
                        
                                /* Define it (parse the class file) */
                                result = defineClass(className, classData, 0, classData.length);
                                if (result == null) {
                                    throw new ClassFormatError();
                                }
                        
                                if (resolveIt) {
                                    resolveClass(result);
                                }
                        
                        //        classes.put(className, result);
                        //        System.out.println("        >>>>>> Returning newly loaded class.");
                                return result;
                            }
                        }
                        • 9. Re: Running Java Inside My IDE
                          807582
                          I forgot - I modified the ClassLoader to allow for re-loading of the same class after making modifications. Standard classloader caches the loaded classes and therfore they cannot be re-loaded. Thats why this sample is called RunItReload.

                          Filip
                          • 10. Re: Running Java Inside My IDE
                            807582
                            Thanks I'm gonna try it later when I'm at home :)
                            • 11. Re: Running Java Inside My IDE
                              807582
                              How do you devide points in here ?
                              • 12. Re: Running Java Inside My IDE
                                807582
                                I tried running your sample but the RunItReload.java produce a :

                                RunItReload.java:74: package com.sun.tools.javac does not exist
                                int compileReturnCode = com.sun.tools.javac.Main.compile(new String[] {sourceFil
                                e});

                                What do I do about it ?
                                • 13. Re: Running Java Inside My IDE
                                  807582
                                  Hi,

                                  You need to have tools.jar in your classpath.

                                  Its available in <java-home>/lib directory.

                                  -Amol
                                  • 14. Re: Running Java Inside My IDE
                                    807582
                                    Sorry I'm not good in classpath how do I do it im my home directory is
                                    c:\Michael\Test
                                    1 2 Previous Next