Executing untokenized command line from Java

前端 未结 2 796
长情又很酷
长情又很酷 2021-01-24 18:37

I am currently using ProcessBuilder to run commands from a java server. This server is to replace an old Perl server, and a lot of our legacy code specifies platform specific c

2条回答
  •  离开以前
    2021-01-24 19:04

    Are you able to use the overloaded Runtime.exec(String) that takes a single String and runs that as the entire command?


    The following works for me on Windows:

    Process p = Runtime.getRuntime().exec("perl -e \"print 5\"");
    System.out.println(IOUtils.toString(p.getInputStream()));
    p.destroy();
    

    This is more or less what Runtime.exec(String) is doing:

    public static void main(String [] args) throws Exception {
        Process p = new ProcessBuilder(getCommand("perl -e \"print 5\"")).start();
        System.out.println(IOUtils.toString(p.getInputStream()));
        p.destroy();
    
    }
    
    private static String[] getCommand(String input) {
        StringTokenizer tokenizer = new StringTokenizer(input);
        String[] result = new String[tokenizer.countTokens()];
        for (int i = 0; tokenizer.hasMoreTokens(); i++) {
            result[i] = tokenizer.nextToken();
        }
        return result;
    }
    

提交回复
热议问题