views:

838

answers:

3

I am looking to create symlinks (soft links) from Java on a Windows Vista/ 2008 machine. I'm happy with the idea that I need to call out to the JNI to do this. I am after help on the actual C code though. What is the appropriate system call to create the link? Pointers to some good documentation on this subject would be very much appreciated.

+2  A: 

Couldn't you just call out to the command line and use mklink?

RB
No! I wish to use the appropriate C/C++ call directly.
David Arno
Fair enough. Is there any specific reason though? I mean, are there features you require that are not available through mklink, or similar?
RB
I mentioned it as an option, its a sensible choice but you do pay an overhead for the process creation.
Scott James
I already have a JNI dll that I need to extend. So just calling the API is far more desirable than spawning a new process to call a separate app, worrying about the path to that app, capturing its return code to know if creation occurred etc.
David Arno
Upon reflection I've changed my down vote to an up vote. I may not want to do it that way, but it isn't a wrong answer and may be useful to others.
David Arno
+4  A: 
Scott James
+7  A: 

Symbolic links in Windows are created using the CreateSymbolicLink API Function, which takes parameters very similar to the command line arguments accepted by the Mklink command line utility.

Assuming you're correctly referencing the JNI and Win32 SDK headers, your code could thus be as simple as:

JNIEXPORT jboolean JNICALL Java_ClassName_MethodName
    (JNIEnv *env, jstring symLinkName, jstring targetName)
{
    const char *nativeSymLinkName = env->GetStringUTFChars(symLinkName, 0);
    const char *nativeTargetName = env->GetStringUTFChars(targetName, 0);

    jboolean success = (CreateSymbolicLink(nativeSymLinkName, nativeTargetName, 0) != 0);

    env->ReleaseStringUTFChars(symLinkName, nativeSymLinkName);
    env->ReleaseStringUTFChars(targetName, nativeTargetName);

    return success;
}

Note that this is just off the top of my head, and I haven't dealt with JNI in ages, so I may have overlooked some of the finer points of making this work...

mdb
Great thanks. That's exactly what I needed.
David Arno