I am trying to run an example to start the CMD. I am getting an error from the execution. The file is of course in the right place. So my guess is that this is a permission error. Can someone lead me on the right track on how to fix this problem?
I am running the program inside eclipse. But the same problem exists when trying to run the jar file.
Exception in thread "main" java.io.IOException: Cannot run program "c:\Windows\system32\cmd.exe /c dir": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048)
at com.test.ProcessBuilderExample.main(ProcessBuilderExample.java:13)
Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified
package com.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.AllPermission;
import java.security.CodeSource;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
public class ProcessBuilderExample {
public static void main(String[] args) throws InterruptedException,
IOException {
ProcessBuilder pb = new ProcessBuilder("c:\\Windows\\system32\\cmd.exe /c dir", "This is ProcessBuilder Example from JCG");
System.out.println("Run echo command");
Process process = pb.start();
int errCode = process.waitFor();
System.out.println("Echo command executed, any errors? " + (errCode == 0 ? "No" : "Yes"));
System.out.println("Echo Output:\n" + output(process.getInputStream()));
}
private static String output(InputStream inputStream) throws IOException {
StringBuilder sb = new StringBuilder();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line + System.getProperty("line.separator"));
}
} finally {
br.close();
}
return sb.toString();
}
}
Copyright Notice:Content Author:「user2130951」,Reproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/48986899/java-run-cmd-security