我想在我的应用程序中以编程方式创建符号链接(symbolic link)。在 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);
}
来自 java.nio.file
但我应该在 Android 中使用什么?
https://docs.oracle.com/javase/tutorial/essential/io/links.html
编辑:
我使用 reflection/native code/OS.symlink() 方法
进行了测试,但没有任何效果。我总是得到 Operation not permitted (EPERM)。我认为您必须拥有 root 权限才能创建符号链接(symbolic link)。
问题可能在于 /mnt/sdcard
是一个包裹 /data/media/xxx
的 FUSE shim。所以我开始使用 /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;
}
或者在 Kotlin 中:
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
}
}
关于java - Android - 在应用程序中创建符号链接(symbolic link),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34608249/