有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

具有包含地址的路径的java执行进程

我使用Runtime.getRuntime().exec()通过Java执行命令,但在运行命令的路径(带空格)方面存在问题

我已经用"(双引号)括住了路径,还尝试了'(单引号),但失败了…:(:)(

我的代码是:

private void encryptFile(String csvFilePath) throws IOException {
    Process proc = Runtime.getRuntime().exec("gpg --recipient testKey2014 --output '" + csvFilePath + ".gpg' --encrypt '" + csvFilePath + "'");
    try {
        proc.waitFor();
    } catch (InterruptedException e) {
        System.out.println(e.getMessage());
    }
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));

    BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));

    String s = null;
    if (stdInput.ready()) {
        // 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);
        }
    }

    if (stdError.ready()) {
        // 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);
        }
    }
}

我还在我的终端中尝试了相同的字符串,它执行得很好,但是这里因为csvFilePath包含(空格),这就是命令不起作用的原因

实际命令是:

gpg --recipient testKey2014 --output '/home/avis/testDir/File Transfers/Recordings/PH2014050401/PH2014050401.zip.gpg' --encrypt '/home/avis/testDir/File Transfers/Recordings/PH2014050401/PH2014050401.zip'

输出为:

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

usage: gpg [options] [filename]

有人建议怎么做吗


共 (1) 个答案

  1. # 1 楼答案

    只需使用array version of exec

    Process proc = Runtime.getRuntime().exec(new String[]{"gpg",
                                                          " recipient",
                                                          "testKey2014",
                                                          " output",
                                                          csvFilePath + ".gpg",
                                                          " encrypt"
                                                          csvFilePath});