Execute a Java program from our Java program

后端 未结 14 1863
名媛妹妹
名媛妹妹 2020-12-01 17:24

I used

Runtime.getRuntime().exec(\"_____\")

but it throws a IOException as below:

java.io.IOException: Create         


        
14条回答
  •  不知归路
    2020-12-01 17:38

    I had to do this recently.
    Here is how I did it, picking up only the relevant parts:

    private static final String[] straJavaArgs =
    {
       "?i/j2re/bin/java",
       "-ms64m",
       "-mx64m",
       "-Djava.ext.dirs=?i/lib;?i/jar/lib;?i/jar"
    };
    
    // ...
    
      // AppDesc appToRun;
      List params = new ArrayList();
      // Java exe and parameters
      params.addAll(ExpandStrings(straJavaArgs));
      // Common VM arguments
      params.addAll(Arrays.asList(AppDesc.GetCommonVMArgs()));
      // Specific VM arguments
      params.addAll(ExpandStrings(appToRun.GetVMArgs()));
      // The program to run
      params.add(appToRun.GetClass());
      // Its arguments
      params.addAll(ExpandStrings(appToRun.GetProgramArgs()));
      // The common arguments
      params.addAll(ExpandStrings(AppDesc.GetCommonProgramArgs()));
    
      ProcessBuilder processBuilder = new ProcessBuilder(params);
      process = processBuilder.start();
      return CaptureProcessOutput(); // Uses a StreamGobbler class
    
    protected ArrayList ExpandStrings(String[] stra)
    {
      ArrayList alResult = new ArrayList();
      for (int i = 0; i < stra.length; i++)
      {
         // Super flexible, eh? Ad hoc for the current task, at least...
         alResult.add(stra[i]
               .replaceAll("\\?i", strInstallDir)
               .replaceAll("\\?c", strConfigDir)
         );
      }
      return alResult;
    }
    
    public enum AppDesc
    {
    // Enumerate the applications to run, with their parameters
    }
    

    Incomplete, if you need more details, just ask.

提交回复
热议问题