Santhosh
Santhosh

Reputation: 534

Deleting a symbolic link in java

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

Upvotes: 3

Views: 8399

Answers (3)

Filip
Filip

Reputation: 661

I'll just go ahead and say that I think that

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

is not correct, at least not completely. Windows do have concept of symbolic and hard link which probably does differentiate in some parts from Unix concept. I could be completely wrong.

But this is not the main point of my reply, I actually ran into same kind of problem, I was not able to remove "symbolic link" which, in fact, was not even symbolic link. I created this symbolic link on Unix and transferred those directories to Windows machine and tried to remove that "symbolic link" with Java NIO, but it failed with java.nio.file.DirectoryNotEmptyException. If I create symbolic link on Windows as instructed in the link above, everything works fine from Java.

I know this is pretty specific scenario, but here's my 2 cents.

Upvotes: 0

xavierraffin
xavierraffin

Reputation: 189

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

Upvotes: 5

MrT
MrT

Reputation: 594

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.

Upvotes: -3

Related Questions