You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android应用开发:如何为外部存储文件设置不可修改的唯一标识

Reliable, User-Unalterable File Identifiers for Android

Great question! When building Android apps that track files across filename changes, you need a persistent identifier tied directly to the file itself—not just its path or name. Below are the most practical, production-ready approaches to solve this:

1. File Content Hash (SHA-256/MD5)

If your processed files are not meant to be edited by users, a cryptographic hash of the file’s content is a rock-solid option. The hash stays identical as long as the file’s content doesn’t change, even if the filename or location is modified.

How to implement:

  • Generate a unique hash (preferably SHA-256 for better collision resistance) when you first save the file.
  • Store this hash in your SQL database alongside other file metadata.
  • To locate the file later, iterate through candidate files, compute their hash, and match it against the stored value.

Example code (Java):

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;

public String calculateFileHash(File file) throws Exception {
    MessageDigest digest = MessageDigest.getInstance("SHA-256");
    FileInputStream fis = new FileInputStream(file);
    byte[] byteArray = new byte[1024];
    int bytesCount;
    
    while ((bytesCount = fis.read(byteArray)) != -1) {
        digest.update(byteArray, 0, bytesCount);
    }
    fis.close();
    
    byte[] bytes = digest.digest();
    StringBuilder sb = new StringBuilder();
    for (byte b : bytes) {
        sb.append(String.format("%02x", b));
    }
    return sb.toString();
}

Pros & Cons:

  • ✅ Completely user-unalterable (short of modifying the file content itself)
  • ✅ Works across all Android versions and file systems
  • ❌ Fails if the user edits the file content (hash will change)
  • ❌ Computing hashes for large files can be slow

2. Extended File Attributes (Xattrs)

Most modern Android file systems (like ext4) support extended attributes—key-value pairs stored directly with the file’s metadata. You can add a custom, app-specific attribute (e.g., com.yourapp.file_uuid) with a unique UUID generated by your app.

How to implement:

  • Generate a UUID when saving the file.
  • Use Android’s Os class to set the extended attribute on the file.
  • Store the UUID in your database; to locate the file later, retrieve the attribute from candidate files and match.

Example code (Java):

import android.system.Os;
import android.system.ErrnoException;
import java.util.UUID;

// Set the custom attribute
public void setFileIdentifier(File file) throws ErrnoException {
    String uuid = UUID.randomUUID().toString();
    Os.setxattr(file.getAbsolutePath(), "com.yourapp.file_uuid", uuid.getBytes(), 0);
    // Store 'uuid' in your database
}

// Retrieve the attribute
public String getFileIdentifier(File file) throws ErrnoException {
    byte[] value = Os.getxattr(file.getAbsolutePath(), "com.yourapp.file_uuid", 0);
    return new String(value);
}

Pros & Cons:

  • ✅ Identifier is tied to the file, not its path/name
  • ✅ Doesn’t modify the file’s content
  • ❌ Not supported on older file systems (e.g., FAT32)
  • ❌ Requires appropriate file system permissions; may not work with Scoped Storage on Android 10+ for external files

3. Embed a UUID in the File Content

If you have full control over the file’s structure (since you’re processing and saving it), embed a unique UUID directly into the file—either at the start, end, or in a dedicated metadata section. This is ideal for custom file formats your app creates.

How to implement:

  • Generate a UUID before saving the processed file.
  • Write the UUID to the file (e.g., append it as a string at the end, or use a structured header for binary files).
  • Store the UUID in your database; when locating the file, read the embedded UUID and match it against the stored value.

Pros & Cons:

  • ✅ Fully under your control; users can’t modify it without editing the file content (which would break its validity for your app)
  • ✅ Works across all file systems and Android versions
  • ❌ Adds a small amount of overhead to the file size
  • ❌ Requires parsing the file content to retrieve the identifier each time

4. MediaStore Content URI (For Media Files)

If your processed files are images, videos, or audio, use Android’s MediaStore to manage them. When you insert a file into MediaStore, the system assigns a unique content URI (e.g., content://media/external/images/media/123) that remains valid even if the user renames the file.

How to implement:

  • Insert the file into MediaStore instead of using File directly.
  • Retrieve the content URI and store its ID (or the full URI) in your database.
  • To access the file later, use the stored URI with ContentResolver.

Pros & Cons:

  • ✅ System-managed identifier; no risk of user modification
  • ✅ Integrates well with Android’s storage system, especially Scoped Storage
  • ❌ Only applicable to media files recognized by MediaStore
  • ❌ Doesn’t work for custom non-media file types

Recommendation

Choose the approach based on your use case:

  • Use embedded UUID if you control the file format (most reliable for custom processed files)
  • Use content hash if file integrity is critical and users won’t edit the files
  • Use MediaStore URI if you’re dealing with standard media files
  • Use extended attributes only if you’re targeting devices with modern file systems and have the necessary permissions

内容的提问来源于stack exchange,提问作者Rohit Rawat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:51:29