Deleting a symbolic link in java

我的梦境 提交于 2019-12-10 11:06:34

问题


Is there any api available to delete a symbolic link using java. Files.delete(Path) didn't work out.Please post your suggestions.


回答1:


Files.delete(Path) is working perfectly on symbolic links. You should have a other issue in your code.

This code sample works (JAVA 8):

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
...
String symLinkName = "/some/path/to/symlink";
try {               
    if(Files.exists(Paths.get(symLinkName))) {              
        Files.delete(Paths.get(symLinkName));
    }
} catch (IOException e) {
    log.info("Cannot delete symbolic link " + symLinkName);
    e.printStackTrace();
}

Remember that symbolic links are a UNIX concept and does not exist on Windows




回答2:


Some more information to symbolic links are found here. If you cant remove the link you can do it with a ProcessBuilder-class in Java and try it with your bash/cmd-command (depends on your used system).

ProcessBuilder pb = new ProcessBuilder("<bash you use>", "rm", "<filepath>");
Process p = pb.start();

But normaly you can delete symbolic links with:

Files.delete("path");

The directory needs to be empty. if the Path is a symbolic link, then the link is deleted and not the target that it represents.



来源:https://stackoverflow.com/questions/32227183/deleting-a-symbolic-link-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!