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.?
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With