ProcessBuilder 启动 java 程序:IOException。无法启动进程。

我有一个像这样的简单类:


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);


   }


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


一只名叫tom的猫
浏览 100回答 1
1回答

holdtom

ProcessBuilder 不使用整个命令行。它需要争论。例如,您当前的代码正在寻找一个基本名称长度为 90 个字符的程序java -cp … Dog.exe。您需要传递一个参数数组:// Note the use of a String array, not a single Stringpublic static void runCode(String... javaArgs) {&nbsp; &nbsp; List<String> args = new ArrayList<>();&nbsp; &nbsp; args.add("java");&nbsp; &nbsp; Collections.addAll(args, javaArgs);&nbsp; &nbsp; ProcessBuilder processBuilder = new ProcessBuilder(args);这可以被调用为:runCode(&nbsp; &nbsp; "-cp",&nbsp; &nbsp; "C:\\Program Files\\Apache Software Foundation\\Tomcat 8.5\\webapps\\Test\\classes",&nbsp; &nbsp; "Dog");另外,不要只打印异常消息。消息本身很少有用。您通常想要打印整个堆栈跟踪,这样您将拥有所有信息并且您将确切地知道问题发生的位置:&nbsp; &nbsp;} catch (IOException ex) {&nbsp; &nbsp; &nbsp; &nbsp;ex.printStackTrace();&nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java