Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rm -rf doesnt work with home tilde in java runtime [duplicate]

Tags:

java

rm

This is my code to delete a folder , this below code wont delete the Downloads directory under 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 complete 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 anybody tell me what am I doing wrong.?

like image 931
stupidosaur Avatar asked Dec 15 '22 18:12

stupidosaur


1 Answers

The tilde (~) is expanded by the shell. When you call exec no shell is invoked, but rather the rm binary is called immediately and thus tildes are not expanded. Nor are wildcards and environment variables.

There are two solutions. Either replace tilde yourself like so:

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

or call a shell by prefixing your command line like so

Runtime.getRuntime().exec("sh -c rm -rf ~/Downloads/2");
like image 77
vidstige Avatar answered Dec 17 '22 07:12

vidstige