Reputation: 9457
I have a video file in the raw folder in my resources. I want to find the size of the file. I have this piece of code:
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());
But it always gives me that the size is 0. What am I doing wrong?
Upvotes: 25
Views: 19391
Reputation: 47069
You can call these on a context or activity. They are exception safe
fun Context.assetSize(resourceId: Int): Long =
try {
resources.openRawResourceFd(resourceId).length
} catch (e: Resources.NotFoundException) {
0
}
This one is not as good as the first, but may be required in certain cases
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
}
}
If you'd like a simple way to get a different byte representation, you can use these
val Long.asKb get() = this.toFloat() / 1024
val Long.asMb get() = asKb / 1024
val Long.asGb get() = asMb / 1024
Upvotes: 2
Reputation: 3520
Slight variation to the answer by @shem
AssetFileDescriptor afd = contentResolver.openAssetFileDescriptor(fileUri,"r");
long fileSize = afd.getLength();
afd.close();
Where fileUri
is of type Android Uri
Upvotes: 10
Reputation: 77722
You can't use File
for resources. Use Resources
or AssetManager
to get an InputStream
to the resource, then call the available()
method on it.
Like this:
InputStream is = context.getResources().openRawResource(R.raw.nameOfFile);
int sizeOfInputStram = is.available(); // Get the size of the stream
Upvotes: 16
Reputation: 4712
Try this:
AssetFileDescriptor sampleFD = getResources().openRawResourceFd(R.raw.video);
long size = sampleFD.getLength()
Upvotes: 24
Reputation: 40381
Try this lines:
InputStream ins = context.getResources().openRawResource (R.raw.video)
int videoSize = ins.available();
Upvotes: 24