Given a symbolic link of
fileA -> fileB
what happens if you try to call file.delete() (the Java 'delete' command) on fileA?
To test what happens, I wrote a test program using Java1.4 on Sun Solaris 8.
Here is the program...
/* Program to test what happens if you try to delete a symbolic
* link from java (running on Solaris)
*
* Command line arguments:
* filename - the symbolic link to delete. (target can be a file or a directory.)
*/
import java.io.*;
public class delete
{
public static void main(String args[])
{
if ( args.length <= 0 )
{
System.out.println("You didn't specify the symbolic link to delete.");
System.out.println("Exiting...");
System.exit(1);
}
String link_name = args[0];
System.out.println("Input Details...");
System.out.println("Symbolic Link: "+link_name);
System.out.println("");
delete d = new delete(link_name);
}
/**
* Constructor
*/
public delete(String link_name)
{
if ( ! exists( link_name ) )
{
System.out.println( link_name + " does not exist.");
System.out.println("Exiting...");
System.exit(1);
}
if ( ! isSymbolicLink( link_name ) )
{
System.out.println( link_name + " is not a symbolic link.");
System.out.println("Exiting...");
System.exit(1);
}
if ( delete(link_name) )
{
System.out.println("Java's File.delete() returned OK.");
}
else
{
System.out.println("Java's File.delete() did NOT work OK.");
}
}
private boolean exists(String link_name)
{
File f = new File( link_name );
return f.exists();
}
private boolean isSymbolicLink(String link_name)
{
try
{
File f = new File( link_name );
if ( ! f.getAbsolutePath().equals( f.getCanonicalPath() ) )
{
return true;
}
else
{
return false;
}
}
catch(IOException e)
{
System.out.println("Exception occurred while trying to determine if " + link_name + "is a symbolic link.");
System.out.println("Can't continue, exiting...");
System.exit(1);
return false;
}
}
private boolean delete(String link_name)
{
File f = new File(link_name);
return f.delete();
}
} // end of class.
The result of my tests were that the symbolic link gets removed (whether the symbolic link points to a file or a directory) but the target object was left untouched.
Note: In the above code, I attempted to identify a symbolic link by comparing the file's absolute path to it's canonical path (see the 'isSymbolicLink(...)' method above). This was the method I had seen suggested several times on the web. Since implementing this method, however, I have determined that it is NOT reliable enough and I am not all that happy with it... (see the following thread in the Java secion of the forums area).