获取Android文件资源的大小?

Ale*_*987 17 size resources android file

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

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());
Run Code Online (Sandbox Code Playgroud)

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

Ale*_*dam 22

试试这一行:

InputStream ins = context.getResources().openRawResource (R.raw.video)
int videoSize = ins.available();
Run Code Online (Sandbox Code Playgroud)

  • `openRawResource()`返回的不是普通的`InputStream`而是`AssetInputStream`.该子类重写`available()`和_is_能够提供可靠的信息. (2认同)

she*_*hem 21

试试这个:

AssetFileDescriptor sampleFD = getResources().openRawResourceFd(R.raw.video);
long size = sampleFD.getLength()
Run Code Online (Sandbox Code Playgroud)

  • 这看起来比其他答案更安全. (4认同)
  • +1但是默认情况下它不会在很多文件类型上工作,因为`aapt`压缩它们 - 对于这里看到的解决方案:http://stackoverflow.com/questions/19743169/how-can-i-使用-openrawresourcesfd/19743170 (3认同)

Ebo*_*ike 11

您不能File用于资源.使用ResourcesAssetManager获取InputStream资源,然后调用该available()方法.

像这样:

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

  • 从来没有遇到过这个问题?!这个方法应该返回"可以读取的估计字节数",不一定是真正的文件大小,文档显然不鼓励使用它... http://developer.android.com/reference/java/io /InputStream.html#available() (12认同)
  • 那么,文档指的是可能需要一段时间才能检索数据的通用流,比如网络流.在资源中,确切的大小始终是已知且可用的. (4认同)

dak*_*aka 8

稍有改变的答案@shem

AssetFileDescriptor afd = contentResolver.openAssetFileDescriptor(fileUri,"r");
long fileSize = afd.getLength();
afd.close();
Run Code Online (Sandbox Code Playgroud)

哪里fileUri是 Android 类型Uri