java runtime.getRuntime.exec( cmd ) with long parameters

后端 未结 3 1447
生来不讨喜
生来不讨喜 2021-01-28 15:35

I\'m making a frontend for a command line app. It has a very long The command line is something simliar to this:

public String liveShellCommand(){

  String cmd         


        
相关标签:
3条回答
  • 2021-01-28 15:57

    Use ProcessBuilder and pass it a String[]

         String[] cmmm = {arg3,arg4,arg5, arg6,arg7 };
         ProcessBuilder pb = new ProcessBuilder(cmmm);
         pb.directory(new File(tDir));
         Process p = pb.start();
    
    0 讨论(0)
  • 2021-01-28 16:06

    +1 for sending the arguments through as an array.

    Sending everything through as a string may work on some systems but fail on others.

    Process start = Runtime.getRuntime().exec(new String[]
    { "java", "-version" });
    BufferedReader r = new BufferedReader(
         new InputStreamReader(start.getErrorStream()));
    String line = null;
    while ((line = r.readLine()) != null)
    {
        System.out.println(line);
    }
    

    I know you have said that you tried sending the arguments through as an array of Strings without success but were you receiving a different type of error? If that other program has a log you might want to see what is going wrong. You could write a simple script that outputs the parameters it was called with to test what is actually coming through.

    0 讨论(0)
  • 2021-01-28 16:18

    an Array was the answer. I also used an ArrayList because of the complexity of the commands. Anyways... Defined arraylist, added commands, converted to array, displayed array, sent commands.. Everything worked well. Each param must be in it's own String within the array.

        List<String> list = new ArrayList<>();
        list.add("command");
        list.add("param");
        String[] command = (String[]) list.toArray(new String[0]);
        log.progress (list);
        run.exec (command);
    
    0 讨论(0)
提交回复
热议问题