获取Android文件资源的大小?

时间:2011-05-18 19:20:40

标签: android file resources size

我的资源中的raw文件夹中有一个视频文件。我想找到文件的大小。 我有这段代码:

Uri filePath = Uri.parse("android.resource://com.android.FileTransfer/" + R.raw.video);
                File videoFile = new File(filePath.getPath());
                Log.v("LOG", "FILE SIZE "+videoFile.length());

但它总是让我觉得大小是0.我做错了什么?

5 个答案:

答案 0 :(得分:22)

试试这一行:

InputStream ins = context.getResources().openRawResource (R.raw.video)
int videoSize = ins.available();

答案 1 :(得分:21)

试试这个:

AssetFileDescriptor sampleFD = getResources().openRawResourceFd(R.raw.video);
long size = sampleFD.getLength()

答案 2 :(得分:11)

您无法将File用于资源。使用ResourcesAssetManager获取资源的InputStream,然后在其上调用available()方法。

像这样:

InputStream is = context.getResources().openRawResource(R.raw.nameOfFile);
int sizeOfInputStram = is.available(); // Get the size of the stream

答案 3 :(得分:2)

可重复使用的Kotlin扩展

您可以根据上下文或活动来调用它们。它们是异常安全的

fun Context.assetSize(resourceId: Int): Long =
    try {
        resources.openRawResourceFd(resourceId).length
    } catch (e: Resources.NotFoundException) {
        0
    }

这个不如第一个好,但是在某些情况下可能是必需的

fun Context.assetSize(resourceUri: Uri): Long {
    try {
        val descriptor = contentResolver.openAssetFileDescriptor(resourceUri, "r")
        val size = descriptor?.length ?: return 0
        descriptor.close()
        return size
    } catch (e: Resources.NotFoundException) {
        return 0
    }
}

如果您想要一种简单的方法来获取不同的字节表示形式,则可以使用这些

val Long.asKb get() = this.toFloat() / 1024
val Long.asMb get() = asKb / 1024
val Long.asGb get() = asMb / 1024 

答案 4 :(得分:1)

answer@shem的轻微变化

(setf *values* '(name :age 1 :len 2 :all '(1 2 3 4 5)))
(destructure *values*
    (type-of age)
    (first all))

其中AssetFileDescriptor afd = contentResolver.openAssetFileDescriptor(fileUri,"r"); long fileSize = afd.getLength(); afd.close(); 是Android Uri类型的