Java运行时中,rm -rf命令不能使用波浪号删除用户主目录。

4
这是我删除一个文件夹的代码,下面这段代码无法删除home文件夹下的Downloads目录。
import java.io.IOException;
public class tester1{   
        public static void main(String[] args) throws IOException {
        System.out.println("here going to delete stuff..!!");
        Runtime.getRuntime().exec("rm -rf ~/Downloads/2");
        //deleteFile();
        System.out.println("Deleted ..!!");     }    
}

但是如果我提供完整的主目录路径,它就可以正常工作:

   import java.io.IOException;
    public class tester1{   
            public static void main(String[] args) throws IOException {
            System.out.println("here going to delete stuff..!!");
            Runtime.getRuntime().exec("rm -rf /home/rah/Downloads/2");
            //deleteFile();
            System.out.println("Deleted ..!!");
        }
        }

有人能告诉我我做错了什么吗?

这段内容涉及it技术,无需修改。

你能把你的错误信息添加进去吗? - ssj
2
可能~没有被扩展为用户主目录。尝试使用System.getProperty("user.home")代替。 - Paolo
4个回答

8

波浪号 (~) 是由 shell 扩展的。当您调用 exec 时,不会调用 shell,而是立即调用 rm 二进制文件,因此波浪号、通配符和环境变量都不会被扩展。

有两种解决方案。要么自己替换波浪号,如下所示:

String path = "~/Downloads/2".replace("~", System.getProperty("user.home"))

或者通过在命令行前加上前缀来调用Shell
Runtime.getRuntime().exec("sh -c rm -rf ~/Downloads/2");

4
仅添加前缀是不够的,因为Runtime.exec(String)存在严重问题,不应使用。执行带有 shell 的方法是:Runtime.getRuntime().exec(new String[] { "sh", "-c", "rm -rf ~/Downloads/2" }); - that other guy
是的,避免引用问题和其他问题会好得多。你在考虑我不知道的其他故障吗? - vidstige
这个命令需要数组版本才能正常工作。如果没有数组版本,该命令等同于 sh -c rm - that other guy

3
波浪号扩展是由shell(例如bash)执行的,但是您直接运行rm命令,因此没有shell来解释波浪号。我强烈建议不要依赖调用shell进行此类功能 - 它们容易出错,具有较差的安全属性并限制代码可以运行的操作系统。
但是,如果您确实决定使用这种特定方法,可以执行以下操作: Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "rm -rf ~/Downloads/2" })

1

您正在使用没有 shell 的 shell 语法。请将命令更改为以下内容:

new String[]{"sh", "-c", "rm -rf ~/Downloads/2"}

这也行不通,因为-c的值必须是“一个字符串”,Java会将其视为“sh”“-c”“rm”“-rf”“〜/ Downloads / 2”,而不是“sh”“-c”“rm -rf〜/ Downloads / 2”,要修复它,OP必须使用exec(new String [] {"sh",“-c”,“rm -rf〜/ Downloads / 2”});。只需修正您的答案即可。 - morgano
@morgano,我已经按建议进行了更改,因为这是更具体方向上的改进,但我不接受“这也行不通”的说法。我只是陈述了命令应该是什么,并且我做得很正确。我没有提到如何拆分命令。 - user207421

0

如果不需要使用波浪符,你可以使用像$HOME这样的环境变量。



String homeDir = System.getenv("HOME"); Runtime.getRuntime().exec("rm -rf " + homeDir + "/Downloads/2");

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接