簡體   English   中英

使用Runtime#exec()編譯和執行Java代碼

[英]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();
        }
    }
}

該程序能夠編譯“ HelloWorld.java”文件,但不能執行該文件(HelloWorld)。 有人可以建議我如何使它工作嗎? 提前致謝! :)另外,如果輸出可以在另一個文本文件中使用,請說“ output.txt”。

運行java程序時,您必須位於項目的根目錄中,並運行java package.to.ClassWhichContainsMainMethod

Runtime.getRuntime().exec()將為您提供一個Process ,該Process包含一個已執行應用程序的OutputStreamInpuStream

您可以將InputStream內容重定向到日志文件。

在您的情況下,我將使用以下exec: public Process exec(String command, String[] envp, File dir)像這樣:

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

要將數據從inputStream復制到文件( 此帖子中被盜的代碼):

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分。

  1. JavaCompiler是Java 1.6中引入的,它允許從Java代碼中直接編譯Java源代碼。
  2. ProcessBuilder(1.5+)是一種更輕松/更強大的啟動Process的方法。
  3. 要處理任何進程,請確保您已閱讀並實現了Runtime.exec()不會的所有要點。

您不在Java中執行“ .java”。 您執行一個類文件。 因此,將第二行更改為:

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

對於輸出,您可能要使用inputStream而不是重定向到文件:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM