开发者

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). Could anyone please suggest me how to make it work? Thanks in Advan开发者_C百科ce! :) Also, if the output could be able to be taken in another text file say 'output.txt'.


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

Runtime.getRuntime().exec() will give you a Process which contains an OutputStream and an InpuStream to the executed application.

You can redirect the InputStream content to your log file.

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

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

To copy data from the inputStream to the file (code stolen on this post) :

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);
    }
}


3 Points.

  1. The JavaCompiler was introduced in Java 1.6 to allow direct compilation of Java source from within Java code.
  2. ProcessBuilder (1.5+) is an easier/more robust way to launch a Process.
  3. For dealing with any process, make sure you read and implement all the points of When Runtime.exec() won't.


You do not execute a ".java" in java. You execute a class file. So 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 might want to use the inputStream:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜