从 Java 程序运行 MS-DOS 命令
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5053766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Run MS-DOS command from java program
提问by Moataz Aahmed Mohammed
How can i run MS-DOS command within my java program ?
如何在我的 Java 程序中运行 MS-DOS 命令?
回答by Maxym
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();
}
}
}
回答by Tomasz Nurkiewicz
Process p = Runtime.getRuntime().exec("cmd /C dir");
BufferedReader stdin = new BufferedReader(new InputStreamReader(p.getInputStream()));
回答by Robert
Use a ProcessBuildereg.
使用ProcessBuilder例如。
Process p = new ProcessBuilder("myCommand", "myArg").start();
Process p = new ProcessBuilder("myCommand", "myArg").start();
This is the Java5 addition that has superseded Runtime.getRuntime().exec()
这是已取代的 Java5 添加 Runtime.getRuntime().exec()
回答by Vivek Goel
use Runtime.getRuntime().exec()
利用 Runtime.getRuntime().exec()