2013-07-22 89 views
12

有沒有辦法讓我的android應用程序檢索和設置文件的擴展用戶屬性?有沒有辦法在android上使用java.nio.file.Files?有什麼方法可以使用我的達爾維克應用程序中的setfattrgetfattr?我知道android使用ext4文件系統,所以我想這應該是可能的。有什麼建議麼?如何在android文件上設置擴展用戶屬性?

回答

12

Android Java庫和仿生C庫不支持它。所以你必須爲Linux系統調用使用本地代碼。

以下是一些示例代碼,讓您開始使用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文件系統不支持的功能,如符號鏈接和擴展屬性。他們可以這樣做,因爲可以通過將設備連接到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"); 
+0

爲什麼第二個拋出一個異常? – Blackbelt

+0

由於谷歌不希望任何超出FAT支持的功能在外部存儲上工作 - 無論是否模擬。這包括符號鏈接,擴展屬性,......它們通過sdcardfs和其他內核功能強制執行。他們可以這樣做,因爲可以通過將設備連接到PC來訪問外部存儲設備,並且用戶期望來回複製文件可以保留所有信息。 –

+0

其實這應該是你的答案的一部分 – Blackbelt

相關問題