问题
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 Advance! :) Also, if the output could be able to be taken in another text file say 'output.txt'.
回答1:
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);
}
}
回答2:
3 Points.
- The JavaCompiler was introduced in Java 1.6 to allow direct compilation of Java source from within Java code.
- ProcessBuilder (1.5+) is an easier/more robust way to launch a Process.
- For dealing with any process, make sure you read and implement all the points of When Runtime.exec() won't.
回答3:
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();
来源:https://stackoverflow.com/questions/3577736/compiling-and-executing-java-code-using-runtimeexec