Run MS-DOS command from java program
How can i run MS-DOS command within my java pr开发者_Go百科ogram ?
How to run command-line or execute external application from Java:
import java.io.*;
public class Main {
public static void main(String args[]) {
try {
Runtime rt = Runtime.getRuntime();
//Process pr = rt.exec("cmd /c dir");
Process pr = rt.exec("c:\\helloworld.exe");
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
while((line=input.readLine()) != null) {
System.out.println(line);
}
int exitVal = pr.waitFor();
System.out.println("Exited with error code "+exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
}
}
Process p = Runtime.getRuntime().exec("cmd /C dir");
BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
Use a ProcessBuilder eg.
Process p = new ProcessBuilder("myCommand", "myArg").start();
This is the Java5 addition that has superseded Runtime.getRuntime().exec()
use Runtime.getRuntime().exec()
精彩评论