我正在尝试运行以下代码来交换文件名。我在用Runtime.exec。代码抛出IOException。反正是为了解决这个问题?
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:运行exec()时出错。命令:file1 1=/mnt/sdcard/fsimage_3,&&,file1 2=/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“工作目录:环境:空
看起来,Runtime.exec在每一次&&之后都会陷入昏迷。看起来问题就在Runtime.exec解释&&的方式上。为什么会发生这种情况?我怎么才能阻止这一切?
发布于 2012-02-28 02:35:36
如果使用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".如果sh不是作为/bin/sh安装的,则使用安装它的路径。
发布于 2018-03-21 06:05:52
首先,问题不是您所认为的“看起来像Runtime.exec在每个&之后插入逗号”,实际上,错误语句是将您在Runtime.exec()中给出的命令作为字符串数组(String[])来报告。这是Java Runtime.exec()方法的标准行为。
02-28 07:48:02.936:
W/System.err(14399): java.io.IOException:
Error runningexec(). 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您可以在错误中看到Java如何解释硬编码的命令,您要返回的字符串数组显示“file2 1=/mnt/sdcard/fsimage 3”被视为要执行的开始命令,其余的“&”、“file2 2=/mnt/sdcard/fsimage”等被视为参数。
我认为您应该首先尝试将命令拆分到类似于结构的数组中。作为下面的例子
Process process;
String[] commandAndArgs = new String[]{ "/bin/sh", "mv", "/mnt/sdcard/fsimages_3","/mnt/sdcard/fsimages" };
process = Runtime.getRuntime().exec(commandAndArgs);接下来,您的错误显示您的工作目录为空,而您的环境也为空。因此,您需要为您的过程设置这两种方法。从Java文档中可以看到它声明了这个exec()重载方法
exec(String[] cmdarray, String[] envp, File dir)在具有指定环境和工作目录的单独进程中执行指定的命令和参数。
如果没有任何声明有效,我请您为您的命令编写一个shell脚本文件,然后使用
chmod 755 or chmod +x script.sh;那就试试吧。我希望它能起作用,就像在我的例子中脚本文件方法一样有效。
https://stackoverflow.com/questions/9475497
复制相似问题