2012-02-28 76 views
3

我想運行下面的代碼來交換文件名。我正在使用Runtime.exec。代碼拋出IOException。有任何解決這個問題的方法嗎?Runtime.exec不工作

try { 
Runtime.getRuntime().exec("file1=" + folderpath + " && file2=/mnt/sdcard/fsimages && temp=\"$(/system/xbin/mktemp -dp /mnt/sdcard)\" && /system/xbin/mv \"$file1\" $temp && /system/xbin/mv \"$file2\" \"$file1\" && /system/xbin/mv $temp/\"$file1\" \"$file2\""); 
} catch (IOException e) { 
    e.printStackTrace(); 
    return; 
} 

和錯誤:

02-28 07:48:02.936: W/System.err(14399): java.io.IOException: Error running exec(). Command: [file1=/mnt/sdcard/fsimages_3, &&, file2=/mnt/sdcard/fsimages, &&, temp="$(/system/xbin/mktemp, -dp, /mnt/sdcard)", &&, /system/xbin/mv, "$file1", $temp, &&, /system/xbin/mv, "$file2", "$file1", &&, /system/xbin/mv, $temp/"$file1", "$file2"] Working Directory: null Environment: null

它看起來像的Runtime.exec之前和之後的每& &插入昏迷。似乎問題的方式是Runtime.exec解釋& &。這是爲什麼發生?我怎樣才能防止這一點?

回答

6

如果使用Runtime.exec(String)重載,則該字符串將被視爲命令及其參數,並在空白邊界處粗分爲子字符串。這種分裂是該超載的標準行爲。 (請參閱javadoc。)

Runtime.exec(...)需要本機命令及其參數。你提供了一行shell輸入。 exec方法不理解shell輸入,也不知道如何正確執行它。粗分裂(見上文)弄亂了一切。

如果你需要做的,然後使用以下命令:

String yourShellInput = "echo hi && echo ho"; // or whatever ... 
String[] commandAndArgs = new String[]{ "/bin/sh", "-c", yourShellInput }; 
Runtime.getRuntime().exec(commandAndArgs); 

這等同於運行:

$ /bin/sh -c "echo hi && echo ho". 
+0

我想'調用Runtime.getRuntime() \t \t \t \t \t \t \t \t \t \t \t \t .exec( 「/ bin/sh的-C(文件1 =」 \t \t \t \t \t \t \t \t \t \t \t \t \t \t + FOLDERPATH \t \t \t \t \t \t \t \t \t \t \t \t \t \t +「&& file2 =/mnt/sdcard/fsimages && temp = \「$(/ system/xbin/mktemp -dp/mnt/sdcard)\」&&/system/xbin/mv \「$ fi le1 \「$ temp &&/system/xbin/mv \」$ file2 \「\」$ file1 \「&&/system/xbin/mv $ temp/\」$ file1 \「\」$ file2 \「)」); 「它仍然沒有工作。我需要一種方法來擺脫這些昏迷。 – 2012-02-28 02:41:29

+0

將'Runtime.exec'作爲邏輯運算符'AND'考慮'&&'作爲邏輯運算符嗎? – 2012-02-28 02:44:22

+0

'02-28 08:21:25.796:W/System.err(14673):java.io.IOException:運行exec()時發生錯誤。命令:[/ bin/sh,-c,(file1 =/mnt/sdcard/fsimages_3,&&,file2 =/mnt/sdcard/fsimages,&&,temp =「$(/ system/xbin/mktemp,-dp,/ mnt/sdcard)「,&&,/ system/xbin/mv,」$ file1「,$ temp,&&,/ system/xbin/mv,」$ file2「,」$ file1「,&&,/ system/xbin/mv ,$ temp /「$ file1」,「$ file2」)] Working Directory:null Environment:null' – 2012-02-28 02:52:08