簡體   English   中英

無法通過Java代碼執行Unix命令

[英]Unable to execute Unix command through Java code

case "BVT Tool":
    System.out.println("Inside BVT Tool");
    try {
        String[] command1 = new String[] {"mv $FileName /bgw/feeds/ibs/incoming/"};
        Runtime.getRuntime().exec(command1);
    } catch(IOException e) {
        System.out.println("execption is :"+ e);
        e.printStackTrace();
    }
    break;

我無法執行Unix命令。 它顯示以下異常:

java.io.IOException: Cannot run program mv $FileName /bgw/feeds/ibs/incoming/":
CreateProcess error=2, The system cannot find the file specified.

我在大多數情況下都同意@Reimeus,但我想指出的是,您收到此特定錯誤消息的原因是exec的兩個重載版本之間存在交叉污染:

String command1 = "mv $FileName /bgw/feeds/ibs/incoming/";
Runtime.getRuntime().exec(command1);

可行- 如果您使用需要一個字符串的重載版本,則可以在一個字符串中指定命令及其參數

String[] command1 = new String[] {"mv", "$FileName", "/bgw/feeds/ibs/incoming/"};
Runtime.getRuntime().exec(command1);

也可以使用,因為它使用的是exec版本,期望使用String數組 該版本要求命令及其參數位於單獨的字符串中

請注意,我在這里假設$Filename實際上是文件的名稱,因此不會進行基於shell的替換。

編輯:如果FileName是變量名,如您似乎在注釋中的其他地方建議,請嘗試

String[] command1 = new String[] {"mv", FileName, "/bgw/feeds/ibs/incoming/"};

但是:使用Commons IO,您可以做

FileUtils.moveFileToDirectory(new File(FileName), new File("/bgw/feeds/ibs/incoming/") , true);

的JavaDoc

這是

  1. 在Mac,Windows和Linux之間完全可移植(您的版本在Windows上不起作用)
  2. 更快,因為它不需要產生外部進程
  3. 出現問題時可為您提供更多信息。

除了Runtime.exec是一種過時的運行命令方法之外,

完整的String被解釋為可執行命令。 您需要在String數組中使用單個標記。 另外,您需要使用外殼程序來解釋$FileName變量

String[] command1 = {"bash", "-c", "mv", "$FileName", "/bgw/feeds/ibs/incoming/"};

首先,您可能應該使用ProcessBuilder 您擁有的命令是“ mv”,其余應為參數,

// I'm not sure about $FileName, that's probably meant to be a shell replace
// and here there is no shell.
ProcessBuilder pb = new ProcessBuilder("mv", 
    System.getenv("FileName"), "/bgw/feeds/ibs/incoming/");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM