1

I am working on my first java project i.e., an TextEditor which can also compile and run files.The compiler (javax.tools.JavaCompiler) is working fine but when I try running ".class" file nothing shows up. I need help in that.

Following is the code for compiling:

public void compileIt(String s)     //s is the absolute path of file to be compiled
    {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        MyDiagnosticListener listener = new MyDiagnosticListener();
             StandardJavaFileManager fileManager =
                compiler.getStandardFileManager(listener, null, null);

        File file;
        file = new File(s);
         String classOutputFolder ="E:\\codefiles";  //destination for storing .class files

        Iterable<? extends JavaFileObject> javaFileObjects = fileManager.getJavaFileObjects(file);
        Iterable options = Arrays.asList("-d", classOutputFolder);
        JavaCompiler.CompilationTask task =
                compiler.getTask(null, fileManager, listener, options, null, javaFileObjects);
        if (task.call()) {
            System.out.println("compilation done");
        }
        try {
            fileManager.close();
        } catch (IOException ex) {
            Logger.getLogger(getName()).log(Level.SEVERE, null, ex);
        }
    }

Code for running the .class files:

void runIt()
{
  String s = null;

        try {


            // using the Runtime exec method:
            Process p = Runtime.getRuntime().exec("java -cp E:\\codefiles");

            BufferedReader stdInput = new BufferedReader(new 
                 InputStreamReader(p.getInputStream()));

            BufferedReader stdError = new BufferedReader(new 
                 InputStreamReader(p.getErrorStream()));

            // read the output from the command

            while ((s = stdInput.readLine()) != null) {
                System.out.println("output is working:\n");
                System.out.println(s);
            }

            // read any errors from the attempted command
           while ((s = stdError.readLine()) != null) {
                System.out.println(s);
            }


        }
        catch (IOException ex1) {
            ex1.printStackTrace();

        }
}
RC_602
  • 21
  • 3

1 Answers1

0

One reason that

 Process p = Runtime.getRuntime().exec("java -cp E:\\codefiles");

does not work is that the command line syntax is wrong. You need to provide a class name as well; e.g.

 Process p = Runtime.getRuntime().exec(
        "java -cp E:\\codefiles  com.example.MyMain");

This assumes that the class you are trying to run has a suitable main method.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216