title: Running a compiled java .class file from within java code and capturing output
body: <p>I'm trying to write a java program with an interface that allows the user to create .java file and compile and run it (essentially a very simplistic IDE). I'm using java swing for the gui and have so far been able to compile a .java file from within the interface into a .class file. I've been researching how to run a .class file from within java code but have found a wide range of answers which I haven't been able to get working. Here is the relevant code for compilation:</p>
  
  <pre><code>File javaFile = new File( "test1.java" );
  String code = entry.getText(); // get text entered by user in GUI
  try{
    PrintWriter writer = new PrintWriter( javaFile );  // write text to .java file  
    writer.print( code );
    writer.close();
  }
  catch( FileNotFoundException e ){
    System.err.println( e );
  }
  JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
  List&lt;File&gt; sourceFileList = new ArrayList&lt;File&gt;();
  sourceFileList.add( javaFile );
  StandardJavaFileManager fileManager = compiler.getStandardFileManager( null, null, null );
  Iterable&lt;? extends JavaFileObject&gt; javaSource = fileManager.getJavaFileObjectsFromFiles( sourceFileList );
  CompilationTask task = compiler.getTask(null, fileManager, null, null, null, javaSource);
  task.call(); // compile .java file into .class file
  </code></pre>
  
  <p>How can I run a compiled .class file and capture its output within my code? </p>