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
其中包含 OutputStream
和一个 InpuStream
到已执行的应用程序。
您可以重定向 InputStream
内容到您的日志文件。
在您的情况下,我会使用此执行程序:public Process exec(String command, String[] envp, File dir)
像这样:
exec("java HelloWorld", null, new File("C:/"));
将数据从 inputStream 复制到文件(代码在 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);
}
}
关于java - 使用 Runtime#exec() 编译和执行 Java 代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3577736/