Steve Bergamini
Steve Bergamini

Reputation: 14600

Symbolic Link Creation in Android Within an Application's Asset Directory

I can't seem to find a solid answer for this specific question.

I'm trying to create a symbolic link programmatically of a directory in my assets folder in another location within the same application's asset directory. Essentially, I'm looking to do the same thing as what the createSymbolicLink method of Java.nio.Files would do.

Is there an available way of doing this with the Android SDK? If not, is it possible in the NDK?

Upvotes: 5

Views: 5456

Answers (2)

android developer
android developer

Reputation: 116332

For Android API 21 and above, just use:

Os.symlink(originalFilePath,symLinkFilePath);

Upvotes: 8

Jared Rummler
Jared Rummler

Reputation: 38121

There is no public API to do this. You can however use some dirty reflection to create your symbolic link. I just tested the following code and it worked for me:

// static factory method to transfer a file from assets to package files directory
AssetUtils.transferAsset(this, "test.png");

// The file that was transferred
File file = new File(getFilesDir(), "test.png");
// The file that I want as my symlink
File symlink = new File(getFilesDir(), "symlink.png");

// do some dirty reflection to create the symbolic link
try {
    final Class<?> libcore = Class.forName("libcore.io.Libcore");
    final Field fOs = libcore.getDeclaredField("os");
    fOs.setAccessible(true);
    final Object os = fOs.get(null);
    final Method method = os.getClass().getMethod("symlink", String.class, String.class);
    method.invoke(os, file.getAbsolutePath(), symlink.getAbsolutePath());
} catch (Exception e) {
    // TODO handle the exception
}

A quick Google search showed this answer if you don't want to use reflection: http://androidwarzone.blogspot.com/2012/03/creating-symbolic-links-on-android-from.html

Upvotes: 3

Related Questions