2014-06-20 27 views
0

我正在使用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] 

任何建議做什麼???

+0

是有什麼像Java **逐字字符串字面:**'@ 「逐字-string字面」 在C#' –

+0

沒有,沒有逐字Java中的字符串。 –

回答

2

只需使用array version of exec

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

+1,工作絕對精細....謝謝你... –