Skip to content Skip to sidebar Skip to footer

Android - Create Symbolic Link In The App

I want create programmatically symbolic link in my app. Is it possible in Android (4.4+)? In Java we can use: Path newLink = ...; Path target = ...; try { Files.createSymbolicL

Solution 1:

Here's a solution that worked for me, which returns true iff succeeded :

publicstaticbooleancreateSymLink(String symLinkFilePath, String originalFilePath) {
    try {
        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            Os.symlink(originalFilePath, symLinkFilePath);
            returntrue;
        }
        final Class<?> libcore = Class.forName("libcore.io.Libcore");
        final java.lang.reflect.FieldfOs= libcore.getDeclaredField("os");
        fOs.setAccessible(true);
        finalObjectos= fOs.get(null);
        final java.lang.reflect.Methodmethod= os.getClass().getMethod("symlink", String.class, String.class);
        method.invoke(os, originalFilePath, symLinkFilePath);
        returntrue;
    } catch (Exception e) {
        e.printStackTrace();
    }
    returnfalse;
}

Or in Kotlin:

companionobject {
    @JvmStaticfuncreateSymLink(symLinkFilePath: String, originalFilePath: String): Boolean {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Os.symlink(originalFilePath, symLinkFilePath)
                returntrue
            }
            val libcore = Class.forName("libcore.io.Libcore")
            val fOs = libcore.getDeclaredField("os")
            fOs.isAccessible = trueval os = fOs.get(null)
            val method = os.javaClass.getMethod("symlink", String::class.java, String::class.java)
            method.invoke(os, originalFilePath, symLinkFilePath)
            returntrue
        } catch (e: Exception) {
            e.printStackTrace()
        }
        returnfalse
    }
}

Solution 2:

Now Android has system calls you can use. Here's android.system.Os.symlink

https://developer.android.com/reference/android/system/Os#symlink(java.lang.String,%20java.lang.String)

there is also the java.nio.file.Files.createSymbolicLink method

https://developer.android.com/reference/java/nio/file/Files#createSymbolicLink(java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.attribute.FileAttribute%3C?%3E...)

but I guess that one didn't really work for you

Post a Comment for "Android - Create Symbolic Link In The App"