Pep*_*tal 5 java filesystems symlink android android-ndk
我想在我的应用中以编程方式创建符号链接。在Android(4.4+)中可以吗?
在Java中,我们可以使用:
Path newLink = ...;
Path target = ...;
try {
Files.createSymbolicLink(newLink, target);
} catch (IOException x) {
System.err.println(x);
} catch (UnsupportedOperationException x) {
// Some file systems do not support symbolic links.
System.err.println(x);
}
Run Code Online (Sandbox Code Playgroud)
从java.nio.file但我应该在Android中使用?
https://docs.oracle.com/javase/tutorial/essential/io/links.html
编辑:
我测试使用reflection/native code/OS.symlink() method,没有任何工作。我总是收到不允许的操作(EPERM)。我认为您必须具有root权限才能创建符号链接。
问题可能/mnt/sdcard在于包装的FUSE垫片/data/media/xxx。所以我开始使用,/data/media/xxx但我总是得到Permission denied
我认为root权限存在问题。
这是一个对我有用的解决方案,当成功时返回 true :
public static boolean createSymLink(String symLinkFilePath, String originalFilePath) {
try {
if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
Os.symlink(originalFilePath, symLinkFilePath);
return true;
}
final Class<?> libcore = Class.forName("libcore.io.Libcore");
final java.lang.reflect.Field fOs = libcore.getDeclaredField("os");
fOs.setAccessible(true);
final Object os = fOs.get(null);
final java.lang.reflect.Method method = os.getClass().getMethod("symlink", String.class, String.class);
method.invoke(os, originalFilePath, symLinkFilePath);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
或者在科特林中:
companion object {
@JvmStatic
fun createSymLink(symLinkFilePath: String, originalFilePath: String): Boolean {
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
Os.symlink(originalFilePath, symLinkFilePath)
return true
}
val libcore = Class.forName("libcore.io.Libcore")
val fOs = libcore.getDeclaredField("os")
fOs.isAccessible = true
val os = fOs.get(null)
val method = os.javaClass.getMethod("symlink", String::class.java, String::class.java)
method.invoke(os, originalFilePath, symLinkFilePath)
return true
} catch (e: Exception) {
e.printStackTrace()
}
return false
}
}
Run Code Online (Sandbox Code Playgroud)