android - 如何在 android 文件上设置扩展用户属性?

标签 android file attributes setattr

我的 Android 应用程序是否可以检索和设置文件的扩展用户属性?有没有办法在 android 上使用 java.nio.file.Files?有什么方法可以从我的 dalvik 应用程序中使用 setfattrgetfattr 吗?我知道 android 使用 ext4 文件系统,所以我想它应该是可能的。有什么建议吗?

最佳答案

Android Java库和bionic C库不支持。因此,您必须为此使用带有 Linux 系统调用的 native 代码。

这里有一些示例代码可以帮助您入门,并在 Android 4.2 和 Android 4.4 上进行了测试。

XAttrNative.java

package com.appfour.example;

import java.io.IOException;

public class XAttrNative {
    static {
        System.loadLibrary("xattr");
    }

    public static native void setxattr(String path, String key, String value) throws IOException;
}

xattr.c

#include <string.h>
#include <jni.h>
#include <asm/unistd.h>
#include <errno.h>

void Java_com_appfour_example_XAttrNative_setxattr(JNIEnv* env, jclass clazz,
        jstring path, jstring key, jstring value) {
    char* pathChars = (*env)->GetStringUTFChars(env, path, NULL);
    char* keyChars = (*env)->GetStringUTFChars(env, key, NULL);
    char* valueChars = (*env)->GetStringUTFChars(env, value, NULL);

    int res = syscall(__NR_setxattr, pathChars, keyChars, valueChars,
            strlen(valueChars), 0);

    if (res != 0) {
        jclass exClass = (*env)->FindClass(env, "java/io/IOException");
        (*env)->ThrowNew(env, exClass, strerror(errno));
    }

    (*env)->ReleaseStringUTFChars(env, path, pathChars);
    (*env)->ReleaseStringUTFChars(env, key, keyChars);
    (*env)->ReleaseStringUTFChars(env, value, valueChars);
}

这在内部存储上运行良好,但在(模拟的)外部存储上运行良好,后者使用 sdcardfs 文件系统或其他内核功能来禁用 FAT 文件系统不支持的功能,例如符号链接(symbolic link)和扩展属性。可以说,他们这样做是因为可以通过将设备连接到 PC 来访问外部存储,并且用户希望来回复制文件可以保留所有信息。

所以这是可行的:

File dataFile = new File(getFilesDir(),"test");
dataFile.createNewFile();
XAttrNative.setxattr(dataFile.getPath(), "user.testkey", "testvalue");

虽然这会抛出 IOException 并显示错误消息:“传输端点不支持操作”:

File externalStorageFile = new File(getExternalFilesDir(null),"test");
externalStorageFile.createNewFile();
XAttrNative.setxattr(externalStorageFile.getPath(), "user.testkey", "testvalue");

关于android - 如何在 android 文件上设置扩展用户属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17784158/

相关文章:

c - 如何在执行过程中向文本文件添加信息? C

c# - 在 dotnet/.NET 中实现自定义属性的最佳方式是什么?

android - 单击按钮后出现 NullPointerException

java - 如何将ArrayList限制为15个?

python - path.exists() 返回 False

python - 如何将字典格式的txt文件转换为python中的数据帧?

asp.net - 获取 ASP.NET 控件的自动生成的名称属性?

Jquery 将相同的 id 定位为单击元素的类名?

java - 编辑文本键盘在双击 grrrrr 时消失

android - 获取 TextView ID 作为字符串