4
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”。

4

3 回答 3

4

当你运行java程序时,你必须在你的项目根目录下,然后运行java package.to.ClassWhichContainsMainMethod

Runtime.getRuntime().exec()会给你一个Process包含一个OutputStream和一个InpuStream已执行应用程序的。

您可以将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);
    }
}
于 2010-08-26T17:31:48.353 回答
3

3 分。

  1. JavaCompiler 是在 Java 1.6 中引入的,以允许从 Java 代码中直接编译 Java 源代码。
  2. ProcessBuilder (1.5+) 是一种更简单/更强大的启动流程的方法。
  3. 为了处理任何进程,请确保您阅读并实施了When Runtime.exec() won't的所有要点。
于 2010-08-26T18:02:44.463 回答
0

您不会在 java 中执行“.java”。你执行一个类文件。所以将第二行更改为:

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

至于输出,您可能希望使用 inputStream,而不是重定向到文件:

InputStream is = Runtime.getRuntime().exec("cd c:\;java HelloWorld").getInputStream();
于 2010-08-26T17:31:42.317 回答