Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Java 與 C 找出 Android 的 SD 卡掛載路徑

編輯:關於 Android 程式設計

Android 的儲存空間配置在不同機種、不同系統版本之間差異極大,硬編碼路徑遲早會出問題。比較可靠的做法是去問系統本身——解析 mount 命令或 vold.fstab 的輸出。以下提供兩種方法,各有 Java 與 C 的實作。

方法一:解析 mount 命令的輸出

先看看 mount 實際回傳什麼:

$ mount
rootfs / rootfs ro,relatime 0 0
tmpfs /dev tmpfs rw,nosuid,relatime,mode=755 0 0
proc /proc proc rw,relatime 0 0
/dev/fuse /mnt/sdcard fuse rw,nosuid,nodev,relatime,user_id=1023,group_id=1023,default_permissions,allow_other 0 0
/dev/block/vold/179:9 /mnt/sdcard-ext vfat rw,dirsync,nosuid,nodev,noexec,relatime,uid=1000,gid=1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0

每一行代表一個掛載點,格式為「裝置 掛載點 檔案系統 參數...」。判斷コツ是:同時出現 /mnt/(或 /storage/)與 vfat 字樣的那一行,很可能就是內建或外接的 SD 卡。

Java 版

// 給 C/C++ 編寫的共享庫回調,取得全部 SD 卡路徑
public String GetAllSDPath() throws TokenException {
    String strMountInfo = "";

    // 1. 先取得系統已加載的文件系統資訊
    try {
        ProcessBuilder objProcessBuilder = new ProcessBuilder();
        // mount -h 可看到說明,直接執行 mount 則會列出已加載的文件系統
        objProcessBuilder.command("mount");
        // 把錯誤輸出併入標準輸出
        objProcessBuilder.redirectErrorStream(true);
        Process objProcess = objProcessBuilder.start();
        objProcess.waitFor();

        // 讀取 mount 命令回傳的資訊
        InputStream objInputStream = objProcess.getInputStream();
        byte[] buffer = new byte[1024];
        while (-1 != objInputStream.read(buffer)) {
            strMountInfo = strMountInfo + new String(buffer);
        }
        objInputStream.close();
        objProcess.destroy();
    } catch (Exception e) {
        e.printStackTrace();
    }

    // 2. 在已加載的文件系統資訊裡找出 SD 卡路徑
    // mount 的輸出是一行一筆,先用換行符拆分
    String[] lines = strMountInfo.split("\n");
    strMountInfo = "";

    for (int i = 0; i < lines.length; i++) {
        // 同時含有 " /mnt/" 與 " vfat " 才可能是 SD 卡
        if (-1 != lines[i].indexOf(" /mnt/") && -1 != lines[i].indexOf(" vfat ")) {
            String[] blocks = lines[i].split("\\s");
            for (int j = 0; j < blocks.length; j++) {
                if (-1 != blocks[j].indexOf("/mnt/")) {
                    // 排除重複路徑
                    if (-1 == strMountInfo.indexOf(blocks[j])) {
                        // 用分號分隔多個 SD 卡路徑
                        strMountInfo += blocks[j] + ";";
                    }
                }
            }
        }
    }
    return strMountInfo;
}

比對字串時刻意在兩側保留空格(" /mnt/"、" vfat "),是為了避免把 /mnt/sdcard-ext 這類延伸字樣誤判進來,同時也避免部分比對造成斷章取義。

C 版

char caStdOutLine[1024];   // mount 命令標準輸出中的一行
char* pcTmpSDPath = NULL;

do   // 非循環,只是為了方便控制分支層次
{
    // popen 會建立管道、fork 子進程並執行 shell 命令,
    // 這個檔案指針必須由 pclose() 關閉。
    FILE* fp = popen("mount", "r");
    if (NULL == fp) {
        break;
    }

    while (NULL != fgets(caStdOutLine, sizeof(caStdOutLine), fp)) {
        // 注意:管道中的資料一定要讀完,否則會阻塞甚至崩潰
        // 若該行含有 " /mnt/" 或 " /storage/",可能是內外置 SD 卡
        if (NULL == strstr(caStdOutLine, " /mnt/") &&
            NULL == strstr(caStdOutLine, " /storage/")) {
            continue;
        }
        if (NULL == strstr(caStdOutLine, " vfat ")) {
            continue;
        }

        pcTmpSDPath = strtok(caStdOutLine, " ");
        do {
            if ((NULL == pcTmpSDPath) || ('\0' == *pcTmpSDPath)) {
                continue;
            }
            if (NULL == strstr(pcTmpSDPath, "/mnt/") &&
                NULL == strstr(pcTmpSDPath, "/storage/")) {
                continue;
            }
            // TODO: 在此使用找到的 SD 卡路徑;
            // 若只需要一個,記得設定「已找到」的旗標
        } while (pcTmpSDPath = strtok(NULL, " "));
    }

    pclose(fp);
} while (0);

方法二:解析 /system/etc/vold.fstab

vold.fstab 是 Android 儲存管理服務的設定檔,宣告了所有可掛載的裝置,格式為:

dev_mount <label> <mount_point> <part> <sysfs_path1...>

實際內容看起來像這樣:

$ cat /system/etc/vold.fstab
# external sd card
dev_mount sdcard-ext /mnt/sdcard-ext auto /devices/platform/sdhci-tegra.2/mmc_host/mmc1

# flash drive connection to USB1
dev_mount usbdisk_1.0 /mnt/usbdisk_1.0 auto /devices/platform/tegra-ehci.0/usb2/2-1/2-1:1.0

這個方法的優點是資訊更結構化:它同時告訴你掛載點、分割區號碼與 sysfs 路徑,也涵蓋了「目前還沒插入但支援的裝置」。缺點是它只描述「可以掛在哪」,不代表「已經掛好」,因此通常還要再搭配 mount 的輸出做二次確認。

C 版

char caStdOutLine[1024];
char* pcTmpSDPath = NULL;
char* pcNotSpace = NULL;

do {
    FILE* fp = popen("cat /system/etc/vold.fstab", "r");
    if (NULL == fp) {
        break;
    }

    while (NULL != fgets(caStdOutLine, sizeof(caStdOutLine), fp)) {
        // Format: dev_mount <label> <mount_point> <part> <sysfs_path1...>
        // 去除行首空格
        pcNotSpace = caStdOutLine + strspn(caStdOutLine, " ");

        // 過濾空行、註解行,以及開頭不是 dev_mount 的行
        if (NULL == pcNotSpace          ||
            '\0' == *pcNotSpace         ||
            '#'  == *pcNotSpace         ||
            'd' != pcNotSpace[0]        ||
            'e' != pcNotSpace[1]        ||
            'v' != pcNotSpace[2]        ||
            '_' != pcNotSpace[3]        ||
            'm' != pcNotSpace[4]        ||
            'o' != pcNotSpace[5]        ||
            'u' != pcNotSpace[6]        ||
            'n' != pcNotSpace[7]        ||
            't' != pcNotSpace[8]) {
            continue;
        }

        // 以空格拆分,第二個欄位就是掛載點
        pcTmpSDPath = strtok(pcNotSpace, " ");
        pcTmpSDPath = strtok(NULL, " ");   // 跳過 label,取 mount_point

        do {
            if ((NULL == pcTmpSDPath) || ('\0' == *pcTmpSDPath)) {
                continue;
            }
            if (NULL == strstr(pcTmpSDPath, "/mnt/") &&
                NULL == strstr(pcTmpSDPath, "/storage/")) {
                continue;
            }
            // TODO: 在此使用找到的 SD 卡路徑
        } while (pcTmpSDPath = strtok(NULL, " "));
    }

    pclose(fp);
} while (0);

更簡單的替代方案

如果只需要「主要的外部儲存位置」,其實不必解析任何命令:Environment.getExternalStorageDirectory() 在大多數情況下就夠用;需要 App 專屬目錄時用 context.getExternalFilesDirs(),它會回傳一組路徑(包含外接 SD 卡),是 API 19 之後官方提供的做法。若要存取任意共用儲存空間,Android 11 之後則應改用 MediaStore 或儲存空間存取架構(SAF),直接操作檔案路徑的方式已不再是推薦做法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved