rm -rf在java运行时不适用于家庭代字号

stu*_*aur 3 java rm

这是我删除文件夹的代码,下面的代码不会删除主文件夹下的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 ..!!");     }    
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我给出完整的主路径,这可行:

   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 ..!!");
        }
        }
Run Code Online (Sandbox Code Playgroud)

谁能告诉我我做错了什么?

vid*_*ige 7

tilde(~)由shell扩展.当你调用时,exec没有调用shell,而是rm立即调用二进制文件,因此不会扩展tildes.通配符和环境变量也不是.

有两种解决方案.要么自己替换代字号:

String path = "~/Downloads/2".replace("~", System.getProperty("user.home"))
Run Code Online (Sandbox Code Playgroud)

或者通过在命令行前加上来调用shell

Runtime.getRuntime().exec("sh -c rm -rf ~/Downloads/2");
Run Code Online (Sandbox Code Playgroud)

  • 前缀是不够的,因为`Runtime.exec(String)`最终被破坏,永远不应该被使用.使用shell执行的方法是`Runtime.getRuntime().exec(new String [] {"sh"," - c","rm -rf~/Downloads/2"});` (4认同)