Rm -rf doesn't work with home tilde in java runtime

This is my code for deleting a folder, this below code does not delete the Downloads directory under the home folder.

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 ..!!");     }    
}

      

However, if I give the full home path, this works:

   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 ..!!");
        }
        }

      

Can someone tell me what I am doing wrong?

+3


source to share


4 answers


The tilde ( ~

) is expanded by the shell. When you call exec

, no wrapper is invoked and the binary rm

is invoked immediately and hence the tildes are not expanded. They are not wildcards and environment variables.

There are two solutions. Alternatively, replace the tilde like this:

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

      



or invoke a shell by first attaching your command line

Runtime.getRuntime().exec("sh -c rm -rf ~/Downloads/2");

      

+7


source


Tilde expansion is done by the shell (like bash), however you are doing it rm

directly so that the shell doesn't interpret ~

. I highly recommend not relying on wrapper calls for such functions - they are error prone, have poor security properties, and limit the operating systems your code can run on.

However, if you do decide to use this particular method, you can do:



Runtime.getRuntime().exec(new String[] { "/bin/bash", "-c", "rm -rf ~/Downloads/2" })

+3


source


You are using shell syntax without shell. Change the command:

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

      

+1


source


You can use an environment variable such as $ HOME if the use of the tilde is not required.



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

0


source







All Articles