use*_*352 1 java shell android rmdir
我的应用程序在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
谁能帮我?
这是因为您使用过Runtime.exec(String)
.切勿使用此功能.这很难预测,只适用于琐碎的案例.一直用Runtime.exec(String[])
.
由于cd
和&&
不是命令而是shell功能,您需要手动调用shell才能使它们工作:
Runtime.getRuntime().exec(new String[] {
"sh", "-c", "cd /mnt/sdcard/mynote && rm -r aaa"
});
Run Code Online (Sandbox Code Playgroud)
在相关的说明中,您永远不应该将未转义的String数据传递给shell.例如,这是错误的:
// Insecure, buggy and wrong!
String target = "aaa";
Runtime.getRuntime().exec(new String[] {
"sh", "-c", "cd /mnt/sdcard/mynote && rm -r " + target
});
Run Code Online (Sandbox Code Playgroud)
正确的方法是将数据作为单独的参数传递给shell,并从命令中引用它们:
// Secure and correct
String target = "aaa";
Runtime.getRuntime().exec(new String[] {
"sh", "-c", "cd /mnt/sdcard/mynote && rm -r \"$1\"", "--", target
});
Run Code Online (Sandbox Code Playgroud)
例如,如果文件被命名,*
或者My file
不正确的版本将删除一大堆完全不相关的文件.正确的版本没有.
归档时间: |
|
查看次数: |
1301 次 |
最近记录: |