2012-02-28 6 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(...)は、ネイティブコマンドとその引数を必要とします。シェル入力の行を指定しました。 execメソッドはシェル入力を理解しておらず、正しく実行する方法を知らない。そして粗製分裂(上記参照)はすべてを駄目にする。

あなたは、次を使用することを行う必要がある場合:

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(FILE1 =" \t \t \t \t \t \t \t \t \t \t \t \t \t \t +フォルダパス \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 $ file1 \ "$ file1 \" &&/system/xbin/mv $ temp/\ "$ file1 \" \ "$ file2 \") "); 'それはまだ働いていない。私はそれらの昏睡を取り除く方法が必要です。 –

+0

'Runtime.exec'は文字列の中の' && 'を論理演算子' AND'とみなしていますか? –

+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、/etc/xbin/mv、 "$ file2"、 "$ file1"、&&、/ system/xbin/mv、/ etc/xbin/mv、 、$ temp/"$ file1"、 "$ file2")] Working Directory:null環境:null ' –

関連する問題