[英]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
包含一個已執行應用程序的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);
}
}
3分。
您不在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.