的Runtime.exec不工作 [英] Runtime.exec not working

查看:293
本文介绍了的Runtime.exec不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图运行下面的code交换文件名。我使用的Runtime.exec 。在code抛出 IOException异常。反正来解决这个问题?

I'm trying to run the following code to swap filenames. I'm using Runtime.exec. The code throws IOException. Anyway to fix this?

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;
}

和错误:

7月2日至二十八日:48:02.936:W / System.err的(14399):java.io.IOException异常:错误
  运行EXEC()。命令:[文件1 =到/ mnt / SD卡/ fsimages_3,和放大器;&安培;,
  文件2 =到/ mnt / SD卡/ fsimages,和放大器;&安培;,TEMP =$(/系统/ XBIN / mktemp的,-dp,
  到/ mnt / SD卡),&安培;&放;, /系统/ XBIN / MV,$文件1,$温度,和放大器;&安培;,
  /系统/ XBIN / MV,$文件2,$文件1,&安培;&放;, /系统/ XBIN / MV,
  $温度/$文件1,$文件2]工作目录:空环境:空

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 的跨$ P $点的&放大器;&安培; 的。这究竟是为什么?我怎样才能prevent呢?

It looks like Runtime.exec is inserting a coma before and after every &&. Seems like the issue is in the way which Runtime.exec interprets &&. Why is this happening? How can I prevent this?

推荐答案

如果您使用的Runtime.exec(字符串)超载,字符串被当作命令和它的参数,并粗暴地分为在空白边界子。这是分裂为超载标准行为。 (请参阅的javadoc。)

If you use the Runtime.exec(String) overload, the string is treated as a command and its arguments, and is crudely split into substrings at white-space boundaries. This splitting is standard behaviour for that overload. (Refer to the javadoc.)

的Runtime.exec(...)预计本机命令及其参数。您提供一个行shell输入。使用exec方法不懂壳输入,不知道如何正确地执行它。而原油裂解(见上文)弄乱了一切。

Runtime.exec(...) expects a native command and its arguments. You've provided a line of shell input. The exec methods don't understand shell input and don't know how to execute it properly. And the crude splitting (see above) messes up everything.

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

If you need to do that, then use the following:

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".

这篇关于的Runtime.exec不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆