先上代码:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class MainTest {
public static void main(String[] args)
{
String cmd = "cmd /c dir d:\\";
StringBuffer sb = new StringBuffer();
try {
Process process = Runtime.getRuntime().exec(cmd);
InputStream is = process.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
process.waitFor();
is.close();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(sb.toString());
}
}
核心就是
Runtime.getRuntime().exec(cmd);
这里的cmd最好以”cmd /c “开头,然后再写想要执行的命令。
因为有一些命令即使能在命令行中正常运行,但是却不能直接运行,而是要通过cmd.exe这个程序才能运行
如果本例中的cmd = "dir d:\\",那么程序就不能正常运行