我正在使用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'
OUTPUT是:
Here is the standard error of the command (if any):
usage: gpg [options] [filename]
有人建议做什么???
答案 0 :(得分:2)
Process proc = Runtime.getRuntime().exec(new String[]{"gpg",
"--recipient",
"testKey2014",
"--output",
csvFilePath + ".gpg",
"--encrypt"
csvFilePath});