Compiling and executing Java code using Runtime # exec ()

import java.io.*; public class Auto { /** * @param args * @throws IOException */ public static void main(String[] args) throws IOException { try { Runtime.getRuntime().exec("javac C:/HelloWorld.java"); Runtime.getRuntime().exec("java C:/HelloWorld > C:/out.txt"); System.out.println("END"); } catch (IOException e) { e.printStackTrace(); } } } 

This program is able to compile the HelloWorld.java file, but not execute it (HelloWorld). Can anyone suggest me how to make it work? Thank you in advance! :) Also, if the output can be done in another text file, say 'output.txt'.

+4
source share
3 answers

When you run the java program, you should be in the root directory of the project and run java package.to.ClassWhichContainsMainMethod

Runtime.getRuntime().exec() will give you a Process that contains the OutputStream and InpuStream in the executed application.

You can redirect the contents of InputStream to a log file.

In your case, I would use this exec: public Process exec(String command, String[] envp, File dir) as follows:

 exec("java HelloWorld", null, new File("C:/")); 

Copy data from inputStream file to file (code is stolen on this message ):

 public runningMethod(){ Process p = exec("java HelloWorld", null, new File("C:/")); pipe(p.getInputStream(), new FileOutputStream("C:/test.txt")); } public void pipe(InputStream in, OutputStream out) { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int writtenBytes; while((writtenBytes = in.read(buf)) >= 0) { out.write(buf, 0, writtenBytes); } } 
+4
source

3 points.

  • JavaCompiler was introduced in Java 1.6 to allow direct compilation of a Java source from Java code.
  • ProcessBuilder (1.5+) is an easier and more reliable way to start a process.
  • To work with any process, make sure that you read and implement all the points When Runtime.exec () will not .
+3
source

You are not running ".java" in java. You are executing a class file. Therefore, change the second line to:

 Runtime.getRuntime().exec("cd c:\;java HelloWorld > C:/out.txt"); 

As for the output, instead of redirecting to a file, you can use inputStream:

 InputStream is = Runtime.getRuntime().exec("cd c:\;java HelloWorld").getInputStream(); 
0
source

All Articles