这是我删除文件夹的代码,下面的代码不会删除主文件夹下的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)
谁能告诉我我做错了什么?
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)