【问题标题】:Fastest way to determine size of directory on SD card on Android在 Android 上确定 SD 卡上目录大小的最快方法
【发布时间】:2011-05-18 06:26:54
【问题描述】:

在 Android 上确定(平面、非嵌套)目录大小的最快、不涉及 hack 的方法是什么?使用 File 对象获取文件列表并通过它们进行枚举以计算大小的速度非常慢 - 肯定有更好的方法吗?

(我知道我可以使用线程在后台计算大小,但在这种情况下这不是一个理想的解决方案)

【问题讨论】:

  • 如果你得到目录File对象的大小会发生什么?我假设您只会获得 FS 条目大小(可能 4 KB 左右),但谁知道...
  • 目录的文件大小未定义。即使它确实在一台设备上给了我我想要的东西,我也不能指望在所有设备上都是如此。

标签: java android


【解决方案1】:

您也可以使用这种方法,类似于建议的另一种方法

public static long getDirSize(File dir) {
    try {
        Process du = Runtime.getRuntime().exec("/system/bin/du -sc " + dir.getCanonicalPath(), new String[]{}, Environment.getRootDirectory());
        BufferedReader br = new BufferedReader(new InputStreamReader(du.getInputStream()));
        String[] parts = br.readLine().split("\\s+");
        return Long.parseLong(parts[0]);
    } catch (IOException e) {
        Log.w(TAG, "Could not find size of directory " + dir.getAbsolutePath(), e);
    }
    return -1;
}

它以千字节为单位返回大小,如果遇到错误,则返回 -1

【讨论】:

  • 这很好用,除了我的parts[0]String,比如1.9G。因此,我没有使用Long.parseLong(parts[0]),而是返回了String 值。
【解决方案2】:

我不知道这对你来说是否属于“非黑客”,但如果你不想重新发明轮子,你可以使用 Linux 命令du。这是来自其manpage的剪辑:

NAME
       du - estimate file space usage

SYNOPSIS
       du [OPTION]... [FILE]...

DESCRIPTION
       Summarize disk usage of each FILE, recursively for directories.

您应该对参数-c-s 感兴趣:

$ du -sc /tmp
164    /tmp
164    total
$

它输出的数字是目录中的总字节数。我不知道您是否想要字节大小或人类可读格式的大小,但如果您也需要,-h 可以为您提供。

您必须读取命令的输出。捕获命令输出已经在this question 中介绍过,我将从中大量借用以提供以下示例:

public String du(String fileName) {
    Class<?> execClass = Class.forName("android.os.Exec");
    Method createSubprocess = execClass.getMethod("createSubprocess", String.class, String.class, String.class, int[].class);
    int[] pid = new int[1];
    FileDescriptor fd = (FileDescriptor)createSubprocess.invoke(null, "/system/bin/du -sc", fileName, null, pid);

    BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(fd)));
    String output = "";
    try {
        String line;
        while ((line = reader.readLine()) != null) {
            output += line + "\n";
        }
    }
    catch (IOException e) {}
    return output;
}

从那里您需要解析输出以获取表示总大小的数值,我将其省略,因为它应该相当微不足道。或者,您可以将其放入 du() 函数中并让该函数返回 int 而不是 String

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-01
    • 1970-01-01
    相关资源
    最近更新 更多