在Android上确定(平面,非嵌套)目录大小的最快,非破解方法是什么?使用File对象获取文件列表并枚举它们来计算大小是无法忍受的慢 - 当然有更好的方法吗?
(我知道我可以使用线程来计算背景中的大小,但在这种情况下这不是理想的解决方案)
答案 0 :(得分:0)
我不知道这对你来说是否属于“非黑客”,但如果你不想重新发明轮子,你可以使用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
。
答案 1 :(得分:0)
您也可以使用此方法,类似于其他提议的方法
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
。你可以