如何从Java引用终端中带空格的文件

时间:2019-07-17 09:18:15

标签: java terminal runtime.exec

我尝试执行命令“ mdls -name kMDItemVersion / Applications / Google \ Chrome.app”或“ / Applications / Google \ Chrome.app/Contents/MacOS/Google \ Chrome --version”已安装的Google Chrome浏览器的正确版本号。

我已经尝试用“ \”对可执行文件和文件夹名称中的空格进行转义,但是在Java中,反斜杠也必须在字符串中进行转义。

这是我用来解决问题的代码:

String s;

try {
    String getChromeVersionArgs = "mdls -name kMDItemVersion /Applications/Google\\ Chrome.app";
    Process process = Runtime.getRuntime().exec(getChromeVersionArgs);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
    BufferedReader stdError = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    // read the output from the command
    System.out.println("Here is the standard output of the command:\n");
    while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
    }
    // read any errors from the attempted command
    System.out.println("Here is the standard error of the command (if any):\n");
    while ((s = stdError.readLine()) != null) {
        System.out.println(s);
    }
    System.exit(0);
} catch (IOException e) {
    System.out.println("exception happened - here's what I know: ");
    e.printStackTrace();
    System.exit(-1);
}

运行此命令时,控制台显示以下文本:

Here is the standard output of the command:

/Applications/Google\: could not find /Applications/Google\.
Here is the standard error of the command (if any):


Process finished with exit code 0

我希望输出为:


Here is the standard output of the command:

Google Chrome 75.0.3770.100

Here is the standard error of the command (if any):


Process finished with exit code 0

无论我使用“ mdls -name kMDItemVersion / Applications / Google \ Chrome.app”还是“ / Applications / Google \ Chrome.app/Contents/MacOS/Google \ Chrome --version”,我应该如何格式化命令?< / p>

0 个答案:

没有答案