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

痴心易碎 提交于 2019-12-20 01:09:03

问题


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?


回答1:


For Android API 21 and above, just use:

Os.symlink(originalFilePath,symLinkFilePath);



回答2:


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



来源:https://stackoverflow.com/questions/27726428/symbolic-link-creation-in-android-within-an-applications-asset-directory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!