当我尝试在java中通过ProcessBuilder运行window的cmd命令时出现错误:

public static void main(String [] args) throws IOException {
	ProcessBuilder builder = new ProcessBuilder();
	Process process = builder.command("dir d:\\").start();
	InputStream inputStream = process.getInputStream();
	
	BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"gb2312"));
	String line = null;
	while((line = br.readLine()) != null) {
		System.out.println(line);
	}
}

出错如下:

Exception in thread "main" java.io.IOException: Cannot run program "dir d:\": CreateProcess error=2, 系统找不到指定的文件。

at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)

at com.xjl456852.processBuilder.ProcessBuilderTest.main(ProcessBuilderTest.java:25)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)

at java.lang.reflect.Method.invoke(Method.java:606)

at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)

Caused by: java.io.IOException: CreateProcess error=2, 系统找不到指定的文件。

at java.lang.ProcessImpl.create(Native Method)

at java.lang.ProcessImpl.<init>(ProcessImpl.java:385)

at java.lang.ProcessImpl.start(ProcessImpl.java:136)

at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028)

... 6 more


即使我把第三行语句改为下面的,仍然出错

Process process = builder.command("cmd.exe /c dir d:\\").start();


后来我看许多人都遇到这种情况,但是没有人说解决方案的,有人就直接放弃了:

所以我又试了各种方式,终于解决了这个问题,这两种方案执行都没有问题.提供给遇到这种问题的朋友一种参考

方法一:

public static void main(String [] args) throws IOException {
	ProcessBuilder builder = new ProcessBuilder();
	List<String> list = new ArrayList<>();
	list.add("cmd.exe");
	list.add("/c");
	list.add("dir");
	list.add("d:\\");
	Process process = builder.command(list).start();
	InputStream inputStream = process.getInputStream();
	
	BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"gb2312"));
	String line = null;
	while((line = br.readLine()) != null) {
		System.out.println(line);
	}
}

方法二:

public static void main(String [] args) throws IOException {
	ProcessBuilder builder = new ProcessBuilder();
	Runtime runtime = Runtime.getRuntime();
	Process process = runtime.exec("cmd.exe /c dir d:\\");
	InputStream inputStream = process.getInputStream();
	
	BufferedReader br = new BufferedReader(new InputStreamReader(inputStream,"gb2312"));
	String line = null;
	while((line = br.readLine()) != null) {
		System.out.println(line);
	}
}