我使用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]
谁有什么建议吗??
使用数组版本的exec:
Process proc = Runtime.getRuntime().exec(new String[]{"gpg",
"--recipient",
"testKey2014",
"--output",
csvFilePath + ".gpg",
"--encrypt"
csvFilePath});