Java Runtime Exec With White Spaces On Path Name

后端 未结 2 1376
悲哀的现实
悲哀的现实 2020-12-22 00:48

I\'m trying to run a OSX command which is plutil to convert certain plist to json format. The command that I use in terminal is

 plutil -convert json -o - \'         


        
相关标签:
2条回答
  • 2020-12-22 01:23

    The call Runtime.getRuntime().exec(cmdStr) is a convenience method - a shortcut for calling the command with an array. It splits the command string on white spaces, and then runs the command with the resulting array.

    So if you give it a string in which any of the parameters includes spaces, it does not parse quotes like the shell does, but just breaks it into parts like this:

    // Bad array created by automatic tokenization of command string
    String[] cmdArr = { "plutil",
                        "-convert",
                        "json",
                        "-o",
                        "-",
                        "'/Users/chris/project/temp",
                        "tutoral/project.plist'" };
    

    Of course, this is not what you want. So in cases like this, you should break the command into your own array. Each parameter should have its own element in the array, and you don't need extra quoting for the space-containing parameters:

    // Correct array 
    String[] cmdArr = { "plutil",
                        "-convert",
                        "json",
                        "-o",
                        "-",
                        "/Users/chris/project/temp tutoral/project.plist" };
    

    Note that the preferred way to start a process is to use ProcessBuilder, e.g.:

    p = new ProcessBuilder("plutil",
                           "-convert",
                           "json",
                           "-o",
                           "-",
                           "/Users/chris/project/temp tutoral/project.plist")
           .start();
    

    ProcessBuilder offers more possibilities, and using Runtime.exec is discouraged.

    0 讨论(0)
  • 2020-12-22 01:38

    Try this

    /Users/chris/project/temp\ tutoral/project.plist
    

    EDIT: I misplaced the backlash on my first post

    0 讨论(0)
提交回复
热议问题