我正在尝试运行以下代码来交换文件名.我正在使用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: 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解释&&的问题.为什么会这样?我怎么能阻止这个?
解决方法:
如果使用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".
标签:android,java,linux
来源: https://codeday.me/bug/20190726/1539802.html