ProcessBuilder启动Java程序:IOException。无法启动进程。原因:无法运行程序CreateProcess错误= 2

时间:2019-07-11 13:54:01

标签: java

我有一个像这样的简单班级:

public class Dog  {
  public static void main(String[] args)  {
    System.out.println("DOG");
    }
}

它被编译到Dog.class内部的C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\Test\classes中。我尝试使用ProcessBuilder运行它:

public static void main(String[] args) {
        String pathName = "-cp \"C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\webapps\\Test\\classes" + "\" " + "Dog";
        runCode(pathName); 
    }
public static void runCode(String name)  {
           System.out.println(name);  //-cp "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\Test\classes" Dog

           ProcessBuilder processBuilder = new ProcessBuilder("java " + name);
           processBuilder.redirectError(new File(Paths.get("C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\webapps\\JavaStudyRooms\\output.txt").toString()));
           processBuilder.redirectInput();

       try {
           final Process process = processBuilder.start();
           try {
               final int exitStatus = process.waitFor();
               if(exitStatus==0){
                   System.out.println("External class  Started Successfully.");
                   System.exit(0); //or whatever suits
               }else{
                   System.out.println("There was an error starting external class. Perhaps path issues. Use exit code "+exitStatus+" for details.");
                   System.out.println("Check also output file for additional details.");
                   System.exit(1);//whatever
               }
           } catch (InterruptedException ex) {
               System.out.println("InterruptedException: "+ex.getMessage());
           }
       } catch (IOException ex) {
           System.out.println("IOException. Faild to start process. Reason: "+ex.getMessage());
       }
       System.out.println("Process Terminated.");
       System.exit(0);

   }

给出错误:

-cp "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\Test\classes" Dog
IOException. Faild to start process. Reason: Cannot run program "java -cp "C:\Program Files\Apache Software Foundation\Tomcat 8.5\webapps\Test\classes" Dog": CreateProcess error=2, Cannot find the file
Process Terminated.

为什么会发生这种情况以及如何解决?

1 个答案:

答案 0 :(得分:1)

ProcessBuilder不会使用整个命令行。需要参数。

您当前的代码正在寻找基本名称为90个字符长的程序,例如java -cp … Dog.exe

您需要传递一个参数数组:

// Note the use of a String array, not a single String

public static void runCode(String... javaArgs) {

    List<String> args = new ArrayList<>();
    args.add("java");
    Collections.addAll(args, javaArgs);

    ProcessBuilder processBuilder = new ProcessBuilder(args);

这可以通过以下方式调用:

runCode(
    "-cp",
    "C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\webapps\\Test\\classes",
    "Dog");

此外,不仅要打印出异常消息。该消息本身很少有用。通常,您需要打印整个堆栈跟踪,因此您将拥有所有信息,并且将确切知道问题发生的位置:

   } catch (IOException ex) {
       ex.printStackTrace();
   }