pass multiple parameters to ProcessBuilder with a space

后端 未结 3 1378
挽巷
挽巷 2020-12-01 17:33

I would like to pass multiple parameters to a processBuilder and the parameters to be separated by a space.

Here is the command,

String[] command_ary         


        
相关标签:
3条回答
  • 2020-12-01 17:46

    Use it like this:

    new java.lang.ProcessBuilder('netstat -an'.toString().split('\\s'))).start()

    0 讨论(0)
  • 2020-12-01 17:51

    You don't need to include spaces. The ProcessBuilder will deal with that for you. Just pass in your arguments one by one, without space:

    ProcessBuilder pb = new ProcessBuilder(
                             dir + "library/crc",
                             "-s",
                             fileName,
                             addressRanges);
    
    0 讨论(0)
  • 2020-12-01 17:53

    We need spaces between arguments in commandline because the commandline need to know which is the first argument, which is the second and so on. However when we use ProcessBuilder, we can pass an array to it, so we do not need to add those spaces to differentiate the arguments. The ProcessBuilder will directly pass the command array to the exec after some checking. For example,

    private static final String JAVA_CMD = "java";
    private static final String CP = "-cp";
    
    private static final String CLASS_PATH = "../bin";
    private static final String PROG = "yr12.m07.b.Test";
    private static final String[] CMD_ARRAY = { JAVA_CMD, CP, CLASS_PATH, PROG };
    ProcessBuilder processBuilder = new ProcessBuilder(CMD_ARRAY);
    

    The above code will work perfectly.

    Moreover, you can use

    Runtime.getRuntime().exec("java -cp C:/testt Test");
    

    But it is more convenient to use ProcessBuilder, one reason is that if our argument contains space we need to pass quote in Runtime.getRuntime().exec() like java -cp C:/testt \"argument with space\", but with ProcessBuilder we can get rid of it.

    ProcessBuilder processBuilder = new ProcessBuilder("command", "The first argument", "TheSecondWithoutSpace");
    
    0 讨论(0)
提交回复
热议问题