gpt4 book ai didi

java - Runtime.exec 不工作

转载 作者:IT王子 更新时间:2023-10-29 00:52:23 27 4
gpt4 key购买 nike

我正在尝试运行以下代码来交换文件名。我正在使用 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 在每个 && 之前和之后插入一个 coma。似乎问题在于 Runtime.exec 解释 && 的方式。为什么会这样?我怎样才能避免这种情况?

最佳答案

如果您使用 Runtime.exec(String) 重载,字符串将被视为命令及其参数,并在空白边界处被粗略地拆分为子字符串。这种拆分是该重载的标准行为。 (请参阅 javadoc。)

Runtime.exec(...) 需要一个 native 命令及其参数。您已经提供了一行 shell 输入。 exec 方法不理解 shell 输入,也不知道如何正确执行它。粗暴的 split (见上文)把一切都搞砸了。

如果您需要这样做,请使用以下命令:

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,请改用安装路径。

关于java - Runtime.exec 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9475497/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com