Tuesday, March 13, 2012

Creating Symbolic links on Android from code

This is only possible using native.
Here is the c code:
#include <string.h>
#include <jni.h>

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

Java_com_netcompss_utils_SymLink_createSymLinkJNI( JNIEnv* env,
                                                  jobject thiz, jstring inputFilePath, jstring inputSymLinkPath )

               const char *inputFilePathC    = (*env)->GetStringUTFChars(env, inputFilePath, 0);
               const char *inputSymLinkPathC = (*env)->GetStringUTFChars(env, inputSymLinkPath, 0);
               int result = symlink(inputFilePathC, inputSymLinkPathC);

              //release resources when done
              (*env)->ReleaseStringUTFChars(env, inputFilePath, inputFilePathC);
              (*env)->ReleaseStringUTFChars(env, inputSymLinkPath, inputSymLinkPathC);
              return result;

Here is the java code:

package com.netcompss.utils;

public class SymLink {
    public  int createSymLink(String filePath,String linkPath) {
        int result = createSymLinkJNI( filePath, linkPath);
        return result;
    public native int  createSymLinkJNI(String filePath,String linkPath);
     static {


Here is an example call:

int result = (new SymLink()).createSymLink("/sdcard/videokit/input_file.mp4", "/sdcard/sym_link.mp4");
        if (result != -1) {
            Log.d(Prefs.TAG, "SymLink creation OK: " + noSpacesValid);
            return noSpacesValid;
        else {
            Log.d(Prefs.TAG, "SymLink creation Failed: " + noSpacesValid);
            return path;

This code was verified on Android 4.0.3