1

我有一个在 SD 卡上有目录的应用程序。应用程序将笔记保存在新的子目录中。我想使用 shell 命令“rm -r”删除整个子目录,但应用程序抛出异常:

04-02 23:14:23.410: W/System.err(14891): java.io.IOException: Error running exec(). Command: [cd, /mnt/sdcard/mynote, &&, rm, -r, aaa] Working Directory: null Environment: null

谁能帮我?

4

1 回答 1

6

发生这种情况是因为您使用了Runtime.exec(String). 切勿使用此功能。这很难预测,只适用于微不足道的情况。始终使用Runtime.exec(String[]).

由于cdand&&不是命令而是 shell 功能,因此您需要手动调用 shell 才能使它们工作:

Runtime.getRuntime().exec(new String[] {
    "sh", "-c", "cd /mnt/sdcard/mynote && rm -r aaa"  
});

在相关说明中,您永远不应该将未转义的字符串数据传递给 shell。例如,这是错误的:

// Insecure, buggy and wrong!
String target = "aaa";
Runtime.getRuntime().exec(new String[] {
    "sh", "-c", "cd /mnt/sdcard/mynote && rm -r " + target  
});

正确的方法是将数据作为单独的参数传递给 shell,并从您的命令中引用它们:

// Secure and correct
String target = "aaa";
Runtime.getRuntime().exec(new String[] {
    "sh", "-c", "cd /mnt/sdcard/mynote && rm -r \"$1\"", "--", target
});

例如,如果一个文件被命名为*or My file,错误的版本将删除一大堆完全不相关的文件。正确的版本没有。

于 2014-04-02T20:33:42.620 回答